简体   繁体   中英

how to specify the return type in a requirement for a concept for types that contains a static constexpr?

This problem is very simmilar to the one described in: C++ concept: Requiring a static variable to be present in a policy class , but the solution does not work for me. My example is the following:

#include <iostream>
template<typename T1>
concept AConcept = requires(T1 a)
{
    // { a.typef }; // without requiring the return type it works.
    { a.typef } -> std::same_as<char>; // not working with char& either.
};

struct Aclass{
    static constexpr char typef='c';
    char getVal(){ return typef; };
};

char getVal( AConcept auto kk ){
    return kk.getVal();
};

int main(){
    Aclass u;
    char c = getVal( u );
    std::cout << c << std::endl;
    return 0;
};

and the compilation fails because the concept requirement is not satisfied. (g++ 11.2.0, compiled with g++ -std=c++20 kk.cpp -o kk )

Thank you in advance,

You can write:

#include <iostream>
#include <type_traits>


template<typename T1>
concept AConcept = std::is_same_v<decltype(std::declval<T1>().typef ), const char>;

struct Aclass{
    static constexpr char typef ='c';

    char getVal(){ return typef; };
};

char getVal( AConcept auto kk ){
    return kk.getVal();
};

int main(){
    Aclass u;
    char c = getVal( u );
    std::cout << c << std::endl;
    return 0;
};

Or if you don't care about the l-value reference you could define the concept like this:

template<typename T1>
concept AConcept = requires(T1 a)
{
    { a.typef } -> std::same_as<const char&>;
};

Have a look at https://en.cppreference.com/w/cpp/language/requires .

The type of the field access expression is const char& - it is the same as: decltype((expression)) .

Have a look at: https://en.cppreference.com/w/cpp/language/decltype The important part here is the ( and ) around the entity which makes it an expression...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM