Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have two (or more) templates that can each adapt a specific set of classes, identified by a concept. To make it possible for the two templates to have the same name, they must be specializations.

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

This works OK when one of the specializations match. When none match the base template is selected, and I get the assertion failure. The mechanism works. I love concepts!

But the error message I get (GCC 7.2.0) points to the assertion. Can I somehow make the base template not be selected, so I would get an error message that tells that no template matched the argument class?

like image 564
Wouter van Ooijen Avatar asked Dec 08 '17 12:12

Wouter van Ooijen


1 Answers

Hurray, I found a solution! What you need is to have the main template constrained:

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> {};

And you get a good diagnostic message:

<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

well, my message is with some dummy constraints, but you get the point

like image 154
bolov Avatar answered Nov 05 '22 10:11

bolov