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

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

我有两个(或更多)模板,每个模板都可以适应一组特定的 classes,由一个概念标识。为了使两个模板可以同名,它们必须是特化的。

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 > . . .

当其中一项专业匹配时,这可以正常工作。当 none 匹配基本模板被选中时,我得到断言失败。该机制有效。我喜欢概念!

但是我得到的错误消息 (GCC 7.2.0) 指向断言。我能不能以某种方式让基本模板不被选中,所以我会收到一条错误消息,告诉我没有模板匹配参数 class?

尝试使用 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 > . . .

万岁,我找到了解决办法!你需要的是约束主模板:

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

好吧,我的信息带有一些虚拟约束,但你明白我的意思