C++ template specialization without default function

anon picture anon · Oct 27, 2009 · Viewed 8.2k times · Source

I have the following code that compiles and works well:

template<typename T>
T GetGlobal(const char *name);

template<>
int GetGlobal<int>(const char *name);

template<>
double GetGlobal<double>(const char *name);

However I want to remove the "default" function. That is, I want to make all calls to GetGlobal<t> where 't' is not an int or a double an error.

For example, GetGlobal<char>() should be a compile time error.

I tried to just delete the default function, but, as I imagined, I received a lot of errors.. So is there a way to "disable" it and allow calls only to the specialized versions of the function?

Thanks!

Answer

Kirill V. Lyadvinsky picture Kirill V. Lyadvinsky · Oct 27, 2009

To get a compile-time error implement it as:

template<typename T>
T GetGlobal(const char *name) { T::unimplemented_function; }
// `unimplemented_function` identifier should be undefined

If you use Boost you could make it more elegant:

template<typename T>
T GetGlobal(const char *name) { BOOST_STATIC_ASSERT(sizeof(T) == 0); }

C++ Standard guarantees that there is no such type which has sizeof equal to 0, so you'll get a compile-time error.

As sbi suggested in his comments the last could be reduced to:

template<typename T>
T GetGlobal(const char *name) { char X[!sizeof(T)]; }

I prefer the first solution, because it gives more clear error message (at least in Visual C++) than the others.