【问题标题】:C++20 Concept test not working in MSVS 16.5C++20 概念测试在 MSVS 16.5 中不起作用
【发布时间】:2020-09-08 17:57:30
【问题描述】:

我是 C++20 概念的新手,但从我看到的示例来看,这段代码应该可以工作......

#include <iostream>
#include <string>
#include <concepts>
#include <memory>

using namespace std;

struct hasToString
{
    string toString()
    {
        return __FUNCTION__;
    }
};

struct noToString
{
};

template<typename T>
concept has_toString = requires(const T & t)
{
    t.toString();
};

template<typename T>
string optionalToString(const T &obj)
{
    if constexpr (has_toString<T>)
        return obj.toString();
    else
        return "toString not defined";
}

int main()
{
    hasToString has;
    unique_ptr<noToString> hasnt = make_unique<noToString>();

    cout << optionalToString(has) << '\n';
    cout << optionalToString(hasnt) << '\n';
}

预期输出:

hasToString::toString

toString 未定义

但我得到了:

toString 未定义

toString 未定义

在这样一个简单的例子中我做错了什么?我选择了 std:c++latest 作为 C++ 语言标准。

【问题讨论】:

    标签: c++ visual-studio c++20 concept


    【解决方案1】:
    concept has_toString = requires(const T & t)
    {
        t.toString();
    };
    

    由于t 是const 对象,其toString() 方法必须是const 方法。这与概念没有直接关系,而是与 C++ 类方法在 C++11 之前的工作方式有关。

    struct hasToString
    {
        string toString()
        {
    

    当然,这个toString() 不是const 类方法。改为将其定义为string toString() const。

    【讨论】:

    • 就是这样。感谢您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2020-09-24
    • 2021-07-12
    • 1970-01-01
    • 2021-10-06
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多