Reputation: 1785
Is it possible to prevent a C++ template being used without specialization?
For example, I have
template<class T>
void foo() {}
And I don't want it to be used without being specialized for foo<int>
or foo<char>
.
Upvotes: 3
Views: 353
Reputation: 1277
You can use undefined type in body of function. And you will get compile time error message:
template<class T> struct A;
template<class T>
void foo()
{
typename A<T>::type a; // template being used without specialization!!!
cout << "foo()\n";
}
template<>
void foo<int>()
{
cout << "foo<int>\n";
}
template<>
void foo<char>()
{
cout << "foo<char>\n";
}
int main()
{
foo<int>();
foo<char>();
// foo<double>(); //uncomment and see compilation error!!!
}
Upvotes: 1
Reputation: 185671
You should be able to declare the function without actually defining it in the generic case. This will cause a reference to an unspecialized template to emit an Undefined Symbol linker error.
template<class T>
void foo();
template<>
void foo<int>() {
// do something here
}
This works just fine for me with clang++
.
Upvotes: 8
Reputation: 39
It's possible when foo function have parameter. for example: template void foo(T param){} now, u can call foo(1), foo('c') without specializing.
Upvotes: -1