[英]Concept that requires a function to return another concept by value or reference
我正在学习 C++ 概念。 现在我可以编写一个需要存在 function 的概念,它返回满足另一个概念的东西,但到目前为止仅按值(在 function getB()
中)。
Function 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();
//...
}
基本上有一个 function 通过引用或值返回满足std::floating_point
之类的概念的东西。 可行吗? 类似于std::is_convertible
的东西可以在那里工作吗?
您可以定义一个接受浮点引用的新概念,如下所示:
template<typename T>
concept FloatingPointReference = std::is_reference_v<T> && std::floating_point<std::remove_reference_t<T>>;
或者,如果您不关心它是按值返回还是按引用返回,您可以检查衰减的类型是否符合该概念。
template<typename T>
concept DecaysToFloatingPoint = std::floating_point<std::decay_t<T>>;
然而,它们都接受可变的 L 值引用,所以这是需要考虑的事情。 例如,您可能想要编写一个仅接受 const 引用和值的概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.