0

Make C++ fail compilation on specific instantiation of template function explains how to make compilation to fail if a function is instantiated with a specific class, but not how to do so with a class.

Say I have a class :

template<class T>
class foo;

And another class Bar. How would I make compilation fail if foo is instantiated or specialized with Bar?

All solutions are like run-time (even though evaluation is at compile time the error can only be given at run- time which is not suitable).

WARhead
  • 643
  • 5
  • 17

3 Answers3

6

If you want an hard compilation error when foo<Bar> is instantiated, you can use static_assert (which also allows you to provide a custom error message):

template <class T>
class foo
{
    static_assert(!std::is_same_v<T, Bar>,
        "foo does not support Bar");
};

live example on wandbox

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
1

Put a static_assert(false, "Class cannot be instantiated with xxx"); in the bad specialization.

struct foo { };
template<typename T>
struct bar_base {
 ...
};
template<typename T>
struct foo : foo_base<T>
{ };
template<>
struct bar<foo>
{
  static_assert(false, "bar cannot be instantiated with foo");
};

Here bar_base holds all the actual implementation.

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23
0

You can do:

template<class T>
class foo {};

struct bar {};

template <>
class foo<bar>;

This declares a specialization for bar but doesn't define it, so anything that tries to cause instantiation will fail. Just make sure to declare this specialization in the same header file as the primary definition of foo, so that it's not possible for a translation unit to see the primary definition but not the specialization.

Nir Friedman
  • 17,108
  • 2
  • 44
  • 72