【问题标题】:Implement error message for trait specialization of class为类的特征特化实现错误消息
【发布时间】:2016-11-07 19:07:43
【问题描述】:

当库用户对模板类的模板参数使用错误类型时,如何实现错误消息?

test.cpp(改编自here

#include <type_traits>
template <typename T, typename Enable = void>
class foo; // Sorry, foo<T> for non-integral type T has not been implemented.

template <typename T>
class foo<T, typename std::enable_if<std::is_integral<T>::value>::type>
{ };

int main()
{
    foo<float> x;
}

代码没有按预期编译。但是我不能让编译器只在用户使用错误类型时才显示错误。

g++ test.cpp的错误信息

test.cpp: In function ‘int main()’:
test.cpp:11:13: error: aggregate ‘foo<float> x’ has incomplete type and cannot be defined
  foo<float> x;

问题:它没有打印出我想要的错误消息 (Sorry, foo&lt;T&gt; for non-integral type T has not been implemented.)

【问题讨论】:

    标签: c++ templates template-specialization sfinae specialization


    【解决方案1】:

    static_assert 可以解决问题:

    template <typename T, typename Enable = void>
    class foo
    {
        static_assert(sizeof(T) == 0, "Sorry, foo<T> for non-integral type T has not been implemented");
    };
    

    Demo

    您需要sizeof(T) == 0,因为始终评估static_assert,并且需要依赖T,否则它将始终触发,即使是有效的T

    【讨论】:

      猜你喜欢
      • 2019-12-08
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多