Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce use of template specialization?

I'm trying to make my template function produce a compile-time error if the non-specialized base version is instantiated. I tried the usual compile-time assert pattern (negative array size) but the compile is failing even when the template is not instantiated. Any thoughts on how to to make it fail if and only if the base-template function is instantiated?

template<class Foo> void func(Foo x) {
  // I want the compiler to complain only if this function is instantiated.
  // Instead, the compiler is complaining here at the declaration.
  int Must_Use_Specialization[-1];
}

template<> void func(int x) {
  printf("Hi\n");
}
like image 720
drwowe Avatar asked Jan 13 '12 16:01

drwowe


People also ask

What is template specialization used for?

It is possible in C++ to get a special behavior for a particular data type. This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming.

How will you restrict the template for a specific datatype?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

Are template specializations inline?

An explicit specialization of a function template is inline only if it is declared with the inline specifier (or defined as deleted), it doesn't matter if the primary template is inline.

Can you partially specialize a C++ function template?

You can choose to specialize only some of the parameters of a class template. This is known as partial specialization. Note that function templates cannot be partially specialized; use overloading to achieve the same effect.


1 Answers

Not defining it is the easiest solution:

template<class Foo> void func(Foo x);

template<> void func(int x) {
  printf("Hi\n");
}

You can also define them in CPP files and use this which will work.

And static assert method:

template<class Foo> void func(Foo x) {
  static_assert(sizeof(Foo) != sizeof(Foo), "func must be specialized for this type!");
}
like image 156
Pubby Avatar answered Sep 22 '22 14:09

Pubby