2

Possible Duplicate:
C++ Restrict Template Function
Is it possible to write a C++ template to check for a function's existence?

Is it possible to restrict the types for which a template may be instantiated (that is, have a compiler error if I use template<type_not_allowed>)?

Community
  • 1
  • 1
Dan Nestor
  • 2,441
  • 1
  • 24
  • 45

2 Answers2

7

One way would be to provide no default implementation, and specialize your class template only on those types you wish to allow. For example:

#include <iostream>
using namespace std;

template<class X> class Gizmo
{
public:
    Gizmo();
};

template<> Gizmo<int>::Gizmo()
{
}

int main()
{
    Gizmo<float> gf; // ERROR:  No specialization for Gizmo<float> results in a linking error
}
John Dibling
  • 99,718
  • 31
  • 186
  • 324
3

Make the constructor private in the illegal type:

template<typename T>
class Z
{
public:
    Z() {}
};

template<>
class Z<int>
{
private:
    Z();
};

Z<float> f; // OK
Z<int>   i; // Compile time error.
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • I wonder if leaving the specialization incomplete wouldn't be simpler and still do the trick? – UncleBens Dec 02 '11 at 16:41
  • @UncleBens, that would produce a linker error (I think this is what you mean: `template<> class Z { public: Z(); };`. As I have it above it produces a compiler error, earlier detection. – hmjd Dec 02 '11 at 16:52
  • 1
    No, I mean `template <> class Z;` You shouldn't be able to instantiate an incomplete type at compile time. (Basically the same - but reversed - as the accepted answer, if the base template was left incomplete.) – UncleBens Dec 02 '11 at 20:36
  • @UncleBens, yes that is an improvement on mine. Less effort to code and compile time error. Cheers. – hmjd Dec 02 '11 at 20:43