gpt4 book ai didi

C++ 模板结构 'has no member named' 错误

转载 作者:行者123 更新时间:2023-11-28 02:31:08 26 4
gpt4 key购买 nike

T==BT==A 时,我可以在不对任何成员 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com