The title is pretty self-explanatory, but here's a simplified example:
#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;
}
The compiler complains when I try to use an anonymous struct as a template argument. What's the best way to achieve something like this without having to have a separate, named struct definition?
You are not allowed to define an unnamed type as a template argument in C++03 or even in C++0x.
The best you can do it to create a named struct local to main (in C++0x1)
1 : You are not allowed to use a local type as template argument in C++03, however C++0x allows it.
Also check out the Defect Report here. The proposed solution mentions
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.
Did you mean template argument? Template parameter is different from template argument.
For example
template < typename T > // T is template parameter
class demo {};
int main()
{
demo <int> x; // int is template argument
}