3

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>.

Tianyang Li
  • 1,755
  • 5
  • 26
  • 42
  • 1
    Uh, just don't use a template? – DarenW Sep 11 '12 at 02:55
  • 2
    @DarenW: You can have specialized templates that are still generic, e.g. `template void foo()` is specialized for any pointer type. – Lily Ballard Sep 11 '12 at 02:56
  • Possible duplicate of [How to prevent non-specialized template instantiation?](http://stackoverflow.com/questions/7064039/how-to-prevent-non-specialized-template-instantiation) – mako Jun 23 '16 at 01:36

3 Answers3

8

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++.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
1

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!!!
}  
SergV
  • 1,269
  • 8
  • 20
-1

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.