使用仅存在于某些数据类型中的字段的C++模板函数?

OJW*_*OJW 5 c++ templates

是否有可能有一个C++模板函数可以访问其输入数据中的不同字段,具体取决于传递给它的输入数据类型

例如,我有以下形式的代码:

typedef struct
{
  int a;
  int b;
}s1;

typedef struct
{
  int a;
}s2;

template <class VTI_type> void myfunc(VTI_type VRI_data, bool contains_b)
{
  printf("%d", VRI_data.a);

  if(contains_b) // or suggest your own test here
    printf("%d", VRI_data.b); // this line won't compile if VTI_type is s2, even though s2.b is never accessed
}

void main()
{
  s1 data1;
  data1.a = 1;
  data1.b = 2;
  myfunc <s1> (data1, true);

  s2 data2;
  data2.a = 1;
  myfunc <s2> (data2, false);
}
Run Code Online (Sandbox Code Playgroud)

所以我们想要使用来自许多不同数据类型的字段A,并且工作正常.

但是,某些数据还有一个需要使用的字段B - 但是如果模板知道它正在查看不包含字段B的数据类型,则需要删除访问字段B的代码.

(在我的示例中,结构是外部API的一部分,因此无法更改)

pet*_*hen 5

详细说明模板专业化的建议用法:

template <class T> void myfunc(T data)
{  
    printf("%d", VRI_data.a);  
}

// specialization for MyClassWithB:
template <>
void myfunc<MyClassWithB>(MyClassWithB data)
{
    printf("%d", data.a);  
    printf("%d", data.b); 
}
Run Code Online (Sandbox Code Playgroud)

但是,这需要每班专业化,没有b的"自动检测".此外,你重复了很多代码.

您可以将"拥有b"方面分解为帮助模板.一个简单的演示:

// helper template - "normal" classes don't have a b
template  <typename T>
int * GetB(T data) { return NULL; }  

// specialization - MyClassWithB does have a b:
template<>
int * GetB<MyClassWithB>(MyClassWithB data) { return &data.b; }

// generic print template
template <class T> void myfunc(T data)
{  
    printf("%d", VRI_data.a);  
    int * pb = GetB(data);
    if (pb)
      printf("%d", *pb); 
}
Run Code Online (Sandbox Code Playgroud)