我有两个(或更多)模板,每个模板都可以适应一组特定的类,由一个概念标识。为了使两个模板具有相同的名称,它们必须是专门化的。
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
好吧,我的信息带有一些虚拟约束,但你明白了
关于C++ 概念和模板特化;如何获得用户友好的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47714655/