Check a template type is in a list of available types

91 views Asked by At

I have a template class Foo. I wrote it template to avoid a huge duplication of code, but this class must be used only with some specific other classes.

How can I check that without C++11 ?

For the moment, the solution I'm going to write is something like that:

template <typename T> inline
bool is_type_available() { return false; }
template <> inline
bool is_type_available<Bar>() { return true; }
template <> inline
bool is_type_available<Baz>() { return true; }

template <typename T>
class Foo
{
  public:
    Foo() { assert(is_type_available<T>()); }
};

I feel it's not so ugly, but I expect something better can exist.

1

There are 1 answers

0
Hcorg On BEST ANSWER

Use Boost libraries (header only):

for example BOOST_STATIC_ASSERT(boost::is_same<T, Bar>::value || boost::is_same<T, Baz>::value);

If list of supported types is longer, either provide them with single base class and use trait is_base_of or check boost MPL library