Reputation: 691
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).
Upvotes: 0
Views: 187
Reputation: 15162
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.
Upvotes: 1
Reputation: 17704
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.
Upvotes: 0
Reputation: 93274
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");
};
Upvotes: 6