当 T==B
时,我可以编译此代码而不对任何成员发出警告的唯一方法等等 T==A
是reinterpret_cast
在 if 语句 block 内并通过指针访问非共享成员。有没有办法解决这个问题或向编译器提示?
这是 gcc 4.8.x
enum Type { A, B};
template<Type T> struct S { };
template<> struct S<A> { int x; int a; };
template<> struct S<B> { int y; int x; int b; };
template<Type T> static void foo(int x)
{
// lots of code
S<T> s;
s.x = someCall();
if (T == A)
{
s.a = 1;
}
else if (T == B)
{
s.y = 2;
s.b = 3;
}
// a bunch of common code
}
编辑:我知道如何制作专用的特定函数来处理具体情况,但我希望避免额外的样板代码。
最佳答案
您可以使用特化:
template <Type T> void bar(S<T>&);
template <> void bar(S<A>& s) {s.a = 1;}
template <> void bar(S<B>& s) {s.y = 2; s.b = 3;}
template<Type T> static void foo(int x)
{
// lots of code
S<T> s;
s.x = someCall();
bar(s);
// a bunch of common code
}
关于C++ 模板结构 'has no member named' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28969942/