Reputation: 440
Local type as template argument is forbidden in C++03:
template<typename T>
struct Foo { };
void Make()
{
struct Unknown {};
Foo<Unknown> foo; // Bad
}
Is there any directives in Standard about checking this rule in case of template is not instantiated?
Is it possible to be sure, that this rule is checked only after template instantiation attempt (no instantiation => compilation success)?
template<typename T>
struct Foo { };
template<typename T>
void Do(T&) { }
template<typename T>
void Do(T*) // usage with pointer is forbidden by-design
{
struct Unknown {};
Foo<Unknown>::UnknownMethod();
}
int main()
{
std::string s;
Do(s);
}
Upvotes: 1
Views: 292
Reputation: 76246
There is no such directive in C++03, because
It is not supposed to be success if the template is not instantiated.
On the other hand, some compilers permit local types as template parameters (e.g. Visual C++; no, it does not follow standard, but that's life), so you can't use that to force compilation failure anyway.
If you need to fail compilation when some combination is attempted, use the standard static assert. You can use the Boost.Static Assert implementation, the implementation linked by πάντα ῥεῖ in comments or the simple implementation in this other question/answer1
template<typename T>
struct Foo { };
template<typename T>
void Do(T&) { }
template<typename T>
void Do(T*) // usage with pointer is forbidden by-design
{
BOOST_STATIC_ASSERT(false);
}
1I am not sure whether it's correct though; I think that implementation may fail even if not instantiated unless the argument is argument-dependent in the enclosing template.
Upvotes: 2