需要一个函数 return 另一个概念的值或引用的概念

Concept that requires a function to return another concept by value or reference

我正在学习 C++ 概念。现在我可以编写一个概念,该概念需要存在一个函数,该函数 returns 满足另一个概念的东西,但到目前为止仅按值(在函数 getB() 中)。

函数 getC() 给出错误,因为:because 'decltype(t.getC())' (aka 'const float &') does not satisfy 'floating_point'because 'is_floating_point_v<const float &>' evaluated to false。毕竟是个参考。

template<typename T>
concept TestConcept =
    requires(T t)
    {
        {t.getA()} -> std::convertible_to<float>;
        {t.getB()} -> std::floating_point;
        {t.getC()} -> std::floating_point;
    };

struct CTest
{
    int a = 10.0f;

    const float& getA() const {return a;}

    const float  getB() const {return a;}
    
    //const float  getC() const {return a;} // This would be OK
    const float& getC() const {return a;} //ERROR
};

我想从这个概念中得到的是:

void func(const TestConcept auto& test){

    std::floating_point c = test.getC();

    //...
}

基本上有一个函数 returns 通过引用或值满足像 std::floating_point 这样的概念的东西。可行吗?类似于 std::is_convertible 的东西可以在那里工作吗?

您可以定义一个接受浮点引用的新概念,如下所示:

template<typename T>
concept FloatingPointReference = std::is_reference_v<T> && std::floating_point<std::remove_reference_t<T>>;

或者,如果您不关心它是 returns 按值还是按引用,您可以检查衰减类型是否符合这个概念。

template<typename T>
concept DecaysToFloatingPoint = std::floating_point<std::decay_t<T>>; 

然而,它们都接受可变的 L 值引用,所以这是需要考虑的事情。例如,您可能想编写一个仅接受 const 引用和值的概念。