在模板类的特定实例化中使编译失败

WAR*_*ead 0 c++ templates compiler-errors class

在模板函数的特定实例化上进行C++失败编译说明如果使用特定类实例化函数而不是如何使用类来实现编译失败.

说我有一节课:

template<class T>
class foo;
Run Code Online (Sandbox Code Playgroud)

而另一个class Bar.如果foo被实例化或专门用于编译,我将如何使编译失败Bar

所有解决方案都像运行时一样(即使评估是在编译时,错误也只能在运行时给出,这是不合适的).

Vit*_*meo 6

如果在foo<Bar>实例化时需要硬编译错误,则可以使用static_assert(这也允许您提供自定义错误消息):

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

wandbox上的实例