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

标签 c++ templates c++-concepts

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

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/

相关文章:

c++ - 使用 C++ 20 概念检查函数是否返回 const 值

c++ - 使用 Poco 库在邮件中发送 HTML 代码

c++ - 模板类的运算符<<()

c++ - GoF 装饰器模式在 C++ 中使用静态多态性(模板)

c++ - 如何使用 type_traits 生成依赖于类特化是否存在的代码?

C++ 概念 : Some signatures function conversion

c++ - 明确的概念特化

c++ - gcc 和 clang STL 实现是否违反有关分配器的规则?

c++ - 为什么从 DLL 内部分配的内存在 FreeLibrary() 之后变得无效?

c++ - 从插槽Blackberry 10中获取TextField-> text()