Make C++ fail compilation on specific instantiation of template function解释了如果使用特定类实例化函数时如何使编译失败,而不是如何对类进行实例化。
假设我有一个类:
template<class T>
class foo;
还有另一个 Bar 类
。如果 foo 被实例化或专门化为 Bar
,我将如何使编译失败?
所有解决方案都像运行时(即使在编译时评估,错误也只能在运行时给出,这是不合适的)。
最佳答案
如果你想在 foo<Bar>
时出现硬编译错误被实例化,你可以使用static_assert
(它还允许您提供自定义错误消息):
template <class T>
class foo
{
static_assert(!std::is_same_v<T, Bar>,
"foo does not support Bar");
};
关于c++ - 使编译在模板类的特定实例化时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48025307/