【问题标题】:make compilation fail on specific instantiation of template class在模板类的特定实例化时使编译失败
【发布时间】:2018-06-10 01:17:54
【问题描述】:

Make C++ fail compilation on specific instantiation of template function 解释了如果使用特定类实例化函数时如何使编译失败,而不是如何使用类。

假设我有一堂课:

template<class T>
class foo;

还有一个class Bar。如果 foo 被实例化或使用Bar 专门化,我将如何使编译失败?

所有解决方案都类似于运行时(尽管评估是在编译时进行的,但错误只能在运行时给出,这是不合适的)。

【问题讨论】:

    标签: c++ class templates compiler-errors


    【解决方案1】:

    如果您希望在实例化foo&lt;Bar&gt; 时出现硬编译错误,您可以使用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 的主要定义相同的头文件中声明此特化,这样翻译单元就不可能看到主要定义而看不到特化。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多