Search code examples
c++constraintsc++20

Constraint (requires) for a template template parameter


How do I constrain the type T when T is not part of the functions signature? E.g. If I want a function that works for arrays of any size.

template<typename T, size_t Size>
requires same_as< T, std::array<int, Size> >
auto foo( const string & str )
{
    T ret;
    for( size_t i = 0; i < Size && i < str.length(); i++ )
        ret[i] = str[i];
    return ret;
}

auto f1 = foo<std::array<int, 3>>( "123"s );
auto f2 = foo<std::array<int, 4>>( "1234"s );

Solution

  • You can write a type trait checking whether a type is a specialization of std::array with the help of partial specialization and use that as a concept

    // primary template for type trait
    template<typename>
    struct is_std_array : std::false_type {};
    
    // partial specialization matching std::array specializations
    template<typename T, std::size_t N>
    struct is_std_array<std::array<T, N>> : std::true_type {};
    
    // concept from the type trait
    template<typename T>
    concept std_array = is_std_array<T>::value;
    
    // use as a concept
    template<std_array T>
    auto foo( const string & str ) {
        /*...*/
    }