好的。这里的代码:
#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/