c++ - 什么 c++ 语法适合通过枚举参数作为模板参数实现嵌套类的函数?

标签 c++ templates enums g++ clang

好的。这里的代码:

#include <iostream>

using namespace std;

template<typename T>
struct A {    
    enum Status {
        one = 1
    };

    template< Status status >
    struct C;
};

template<typename T>
template<typename A<T>::Status status >
struct A<T>::C {
    void operator()() {
        cout << "C: " << (int)status << endl;
    };

//    void operator()();
};

// template<typename T>
// template<typename A<T>::Status status >
// void A<T>::C<status>::operator()() {
//    cout << "C: " << status << endl;
//}

int main()
{   
    A<int>::C<A<int>::one> c;
    c();

    return 0;
}

它与 clang 和 g++ 一起工作 - 编译和运行。

但是,如果注释内联实现 A::C::operator()(),并且取消注释注释声明和输出实现:

#include <iostream>

using namespace std;

template<typename T>
struct A {    
    enum Status {
        one = 1
    };

    template< Status status >
    struct C;
};

template<typename T>
template<typename A<T>::Status status >
struct A<T>::C {
//    void operator()() {
//        cout << "C: " << (int)status << endl;
//    };

    void operator()();
};

template<typename T>
template<typename A<T>::Status status >
void A<T>::C<status>::operator()() {
    cout << "C: " << status << endl;
}

int main()
{   
    A<int>::C<A<int>::one> c;
    c();

    return 0;
}

clang 不会这样做:

$ clang++ -std=c++11 main.cpp && ./a.out
main.cpp:28:23: error: nested name specifier 'A<T>::C<status>::' for declaration does not refer into a class, class template or class template partial specialization
void A<T>::C<status>::operator()() {
     ~~~~~~~~~~~~~~~~~^
1 error generated.

但是 g++ 确实有效:

$ g++-4.8 -std=c++11 -O2 -Wall -pedantic -pthread main.cpp
C: 1

我尝试在工作 PC 上使用 Visual C++ 2010 编译代码,但两个示例都失败了。我现在无法验证(没有 Windows PC)而且我不确定 - 也许我犯了其他错误...

第二个示例中的错误在哪里以及实现的正确语法是什么?

最佳答案

在我看来,您只是在 struct C 的实现中忘记了模板参数。 以下固定代码在 Visual C++ 2010 中编译文件:

#include <iostream>
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

template<typename T>
struct A {    
    enum Status {
        one = 1
    };

    template< Status status >
    struct C;
};

template<typename T>
template<typename A<T>::Status status >
struct A<T>::C<status> {
    /*void operator()() {
        cout << "C: " << (int)status << endl;
    };*/

    void operator()();
};

template<typename T>
template<typename A<T>::Status status >
void A<T>::C<status>::operator()() {
    cout << "C: " << status << endl;
}

int main()
{   
    A<int>::C<A<int>::one> c;
    c();

    return 0;
}

关于c++ - 什么 c++ 语法适合通过枚举参数作为模板参数实现嵌套类的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23938138/

相关文章:

php - 为什么我在 Laravel View 中得到 "Undefined variable"?

c++ - 我可以将其模板化以避免重写类吗?

c# - 如何使用枚举进行版本控制

c++ - 为什么 GCC 不能消除多个继承函数的歧义(但 clang 可以)?

c++ - 我应该如何将我的长函数移出 MainWindow (QT)

c++ - 如何在子类的 vector 上应用多态函数

c++ - C++模板类问题中的类型条件

c# - 以枚举为键绑定(bind)到字典中的值

c# - 使用 EnumToList<T> 时如何将 <T> 转换为 Enum

c++ - opencv中的这个语句是什么意思?