C 概念和模板专业化;如何获得用户友好的编译器错误

C++ concepts and template specialization; how to get a user-friendly compiler error

本文关键字:用户 何获得 错误 编译器 专业化      更新时间:2023-10-16

我有两个(或多个)模板,它们每个模板都可以调整一组由概念标识的特定类。为了使两个模板具有相同的名称,它们必须是专业。

template< typename T >
struct pin_in { static_assert( always_false<T>::value, . . . ); };  
template< is_pin_in T >
struct pin_in< T > . . .
template< is_pin_in_out T >
struct pin_in< T > . . .

当专业之一匹配时,这可以正常工作。当不匹配基本模板时,我会得到断言失败。该机制起作用。我喜欢概念!

但是,我收到的错误消息(GCC 7.2.0)指向断言。我可以以某种方式不选择基本模板,因此我会收到一条错误消息,该消息告诉没有模板与参数类匹配?

欢呼,我找到了解决方案!您需要的是将主要模板限制为限制:

template <class T>
    requires is_pin_in<T> || is_pin_in_out<T>
struct pin_in {};

template <is_pin_in T>
struct pin_in<T> {};
template <is_pin_in_out T>
struct pin_in<T> {};

您会收到一条很好的诊断消息:

<source>: In function 'auto test()':
29 : <source>:29:16: error: template constraint failure
     pin_in<char> a;
                ^
29 : <source>:29:16: note:   constraints not satisfied
7 : <source>:7:24: note: within 'template<class T> concept const bool is_pin_in<T> [with T = char]'
 constexpr concept bool is_pin_in = std::is_same_v<T, int>;
                        ^~~~~~~~~
7 : <source>:7:24: note: 'std::is_same_v' evaluated to false
9 : <source>:9:24: note: within 'template<class T> concept const bool is_pin_in_out<T> [with T = char]'
 constexpr concept bool is_pin_in_out = std::is_same_v<T, unsigned>;
                        ^~~~~~~~~~~~~
9 : <source>:9:24: note: 'std::is_same_v' evaluated to false
Compiler exited with result code 1

好吧,我的消息有一些虚拟约束,但是您得到了点

尝试使用std :: enable_if从过载分辨率中删除基本模板。这样的东西:

template< typename T >
struct pin_in<typename std::enable_if<false>::type> {};  
template< is_pin_in T >
struct pin_in<typename std::enable_if<true>::type>< T > . . .
template< is_pin_in_out T >
struct pin_in<typename std::enable_if<true>::type>< T > . . .