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");
}
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.
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.
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.
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.
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!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With