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

标签 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);
}

所以我们想使用来自许多不同数据类型的字段 A,而且效果很好。

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

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

最佳答案

详细说明模板特化的建议用途:

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); 
}

但是,这需要每个类的专门化,没有 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); 
}

关于使用仅存在于某些数据类型中的字段的 C++ 模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1142658/

相关文章:

c++ - Doxygen 提示递归 C++ 类

c++ - 如何确定一个类是否包含子类/类型?

c++ - 管理异步通信: how to examine response received in another thread

c++ - 如何在 Windows 下使用 C++ 在多个扬声器上播放声音?

c++ - 使用 C 的 '...' 参数包作为 C++ 模板值?

c++ - 如何专门化模板构造函数

C++ void_t SFINAE false_type true_type 无法获得特化

c++ - libev + 非阻塞socket 持续调用回调

C++ 字符串 char** 翻译

c++ - 在旧版本的 boost 中使用 recursive_directory_iterator ?