C++如何将std::function与不同返回类型的重载运算符一起使用

我正在尝试将标准std::function与自定义重载运算符一起使用。但是std::logical_and,在这种情况下Test,将string参数应用于我的班级是行不通的。

class Test {
public:
    std::string value;

    Test(std::string cvalue) : value(cvalue) {}

    std::string operator&& (const std::string& rhs) const {
        if (rhs == value) {
            return "true";
        }
        return "false";
    }
};

int main() {
    Test test("hey");
    std::string out = std::logical_and<std::string>()(test, "hey");
    std::cout << out << std::endl;
    return 0;
}

实现这一目标的正确方法是什么?我的预期输出是"true"

回答

You need to use std::logical_and<> to allow deduction for both arguments and return type:

std::string out = std::logical_and<>()(test, "hey");

Demo


以上是C++如何将std::function与不同返回类型的重载运算符一起使用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>