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

make compilation fail on specific instantiation of template class

本文关键字:实例化 失败 编译      更新时间:2023-10-16

使C++失败 在模板函数的特定实例化上编译解释了如果使用特定类实例化函数,如何使编译失败,但不知道如何使用类进行编译失败。

假设我有一堂课:

template<class T>
class foo;

还有另一个class 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");
};

魔杖盒上的现场示例

在糟糕的专业化中放置一个static_assert(错误,"类不能用 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保存了所有实际的实现。

你可以做:

template<class T>
class foo {};
struct bar {};
template <>
class foo<bar>;

这声明了bar的专用化,但没有定义它,因此任何试图导致实例化的东西都将失败。只需确保在与foo的主要定义相同的头文件中声明此专用化,以便翻译单元无法看到主要定义,但看不到专用化。