标题很简单,但这里是一个简单的例子:
#include <cstdio> template <typename T> struct MyTemplate { T member; void printMemberSize() { printf("%i\n",sizeof(T)); } }; int main() { MyTemplate<struct { int a; int b; }> t; // <-- compiler doesn't like this t.printMemberSize(); return 0; }
当我尝试使用匿名结构作为模板参数时,编译器会抱怨.什么是最好的方式来实现这样的东西,而不必有一个单独的,命名的结构定义?
解决方法
您不能在C 03或甚至C 0x中将未命名的类型定义为模板参数.
最好的方法是创建一个名为struct的main(在C 0x1中)
1:您不能在C 03中使用本地类型作为模板参数,但是C 0x允许.
The following types shall not be used as a template-argument for a template type-parameter:
- a type whose name has no linkage
- an unnamed class or enumeration type that has no name for linkage purposes (7.1.3 [dcl.typedef])
- a cv-qualified version of one of the types in this list
- a type created by application of declarator operators to one of the types in this list
- a function type that uses one of the types in this list
The compiler complains when I try to use an anonymous struct as a template parameter.
你的意思是模板参数?模板参数与模板参数不同.
例如
template < typename T > // T is template parameter class demo {}; int main() { demo <int> x; // int is template argument }