是否有可能有一个 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/