3
votes

I'm currently experimenting with the new c++2a 'concepts' feature. The goal of my code below is to check some property of a templated struct. As the first template argument is 'reserved' for the type to be checked, I have difficulties using the concept without a requires expression or specifying template arguments manually. This is not a big deal, but I like the concept notation for its clarity. Is there a way to work around this?

Compiler

gcc-g++-10.0 (GCC) 10.0.1 20200119 (experimental)
Copyright (C) 2020 Free Software Foundation, Inc.

Compile command

g++-10.0 -std=c++2a file.cc

Code


#include <concepts>

/// Struct has template arguments and a property that can be checked in a concept.
template <bool a> struct A {
  constexpr static bool property() noexcept { return a; }
};

template <typename T, bool a> concept hasProp = std::is_same_v<T, A<a>> && A<a>::property();

template <bool a> requires hasProp<A<a>, a> void works(A<a> c) {} 
template <bool a, hasProp<a> c> void deductionError(c d) {};

// This is a sketch of what I'd like to do:
// template <A<a, b> Class, bool a, bool b> concept hasProp = Class::property;

int main() {
  A<true> a;
  A<false> b;

  works(a);
  //works(b); //doesn't compile as the constraint is not fulfilled, which is desired.

  //deductionError(a); // I get why this deduction error occurs, but is it possible to do this
                      // in a clean way using concepts without having so specify template arguments?
}

2

2 Answers

2
votes

Partial class template specializations to the rescue:

template<class T> 
struct HasProp : std::false_type{};

template<bool a>
struct HasProp<A<a>> : std::integral_constant<bool, A<a>::property()>
{};

template <class T> 
concept hasProp = HasProp<T>::value;

template <bool a> 
requires hasProp<A<a>>
void works(A<a>) {}

template<hasProp C> 
void deductionError(C){} // no longer a deductionError

Demo


This does (perhaps needlessly) tie your concept to A directly.

You could instead do this (Like @Barry answered):

template <class T> 
concept hasProp = T::property();

Demo2

2
votes

Do you really need the tie-in to A?

template <typename T> concept hasProp = T::property();

template <bool a> requires hasProp<A<a>> void works(A<a>); // ok
template <hasProp C> void deductionError(C);               // also ok

If you do need the tie-in, you can add that entirely local to hasProp:

// unfortunately this is hard to generalize due to the non-type template parameter
template <typename T> struct is_A : std::false_type { };
template <bool b> struct is_A<A<b>> : std::true_type { };

template <typename T> concept hasProp = is_A<T>::value && T::property();

// ... and the rest works as before
template <bool a> requires hasProp<A<a>> void works(A<a>); // ok
template <hasProp C> void deductionError(C);               // also ok

Either way, hasProp should just take a type.