【问题标题】:make compilation fail on specific instantiation of template class在模板类的特定实例化时使编译失败
【发布时间】:2018-06-10 01:17:54
【问题描述】:
【问题讨论】:
标签:
c++
class
templates
compiler-errors
【解决方案1】:
如果您希望在实例化foo<Bar> 时出现硬编译错误,您可以使用static_assert(它还允许您提供自定义错误消息):
template <class T>
class foo
{
static_assert(!std::is_same_v<T, Bar>,
"foo does not support Bar");
};
live example on wandbox
【解决方案2】:
放一个static_assert(false, "类不能用xxx实例化");在糟糕的专业化中。
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");
};
这里 bar_base 包含所有实际的实现。
【解决方案3】:
你可以这样做:
template<class T>
class foo {};
struct bar {};
template <>
class foo<bar>;
这声明了bar 的特化,但没有定义它,所以任何试图导致实例化的东西都会失败。只需确保在与foo 的主要定义相同的头文件中声明此特化,这样翻译单元就不可能看到主要定义而看不到特化。