提问者:小点点

无法生成需要bool成员函数的C++20概念[重复]


这个MCVE在Visual Studio(2019,C++20标志打开)和G++10(同样,C++20选项设置)中都遇到了麻烦。 每种情况下的抱怨都是bool不是类型约束。 (那么,我应该键入什么来要求给定类型具有这样的成员函数呢?)

#include <concepts> 

template <typename T>
concept testable = requires(T t)
{
    { t.foo() } -> bool; //Error is here: "expected a concept" or
                         //  "return-type-requirement is not a type-constraint"
};

class A
{
public:
    bool foo() const { return true; }
};

template<testable T>
void verify(const T& t) { assert(t.foo()); }

int main(void)
{
    A a; verify(a);
    return 0;
}

共1个答案

匿名用户

这个概念需要写成:

template <typename T>
concept testable = requires(T t)
{
    { t.foo() } -> std::convertible_to<bool>; 
};

请注意,这实际上在foo的约束中更为明确。 它说,调用foo必须返回可转换为bool的类型。

这意味着您还可以指定返回值应该是一个bool,如果您想这样做的话:

template <typename T>
concept testable = requires(T t)
{
    { t.foo() } -> std::same_as<bool>; 
};

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(生成|bool|成员|函数|c++20|概念|重复)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?