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

标签 c++ templates c++11

T==B 时,我可以编译此代码而不对任何成员发出警告的唯一方法等等 T==Areinterpret_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/

相关文章:

c++ - Qt4 Designer 使用 QTableWidget 创建对话框

c++ - 使用 Proc 文件计算 %CPU 使用率

c++ - 模板类的转换

c++ - 在可变参数模板函数中同时接受 int 和 class?

c++ - 显式默认构造函数

C++11 获取 unordered_map 中一个存储桶的所有项目

c++ - 为什么 stoi 比没有 -O3 的 stringstream 慢得多?

c++ - 是否可以删除非新对象?

c++ - 重载括号运算符作为成员函数

django - 为什么使用 django TemplateTag 标签?