使用超载方法使用std :: result_of

Using std::result_of with an overloaded method

本文关键字:of result std 超载 方法      更新时间:2023-10-16

我在现有类中添加了一个超载方法,该类别现在在我们的单元测试中导致汇编错误。

我已经使用以下代码复制了问题:

#include <type_traits>
#include <string>
class Foo
{
    public:
    Foo() {};
    int bar(const std::string & s) {return 1;};
    int bar(const std::string & s, long l) {return 2;};
    int bar2(const std::string & s) {return 3;};
};
int main()
{
    // compiles
    std::is_same<std::result_of<decltype(&Foo::bar2)(Foo, const std::string &)>::type, int>::value;
    // does not compile
    std::is_same<std::result_of<decltype(&Foo::bar)(Foo, const std::string &)>::type, int>::value;
    return 0;
}

我需要对不编译的行进行哪些更改,以便我可以测试超载方法的返回?

一个超载函数名称代表所有过载,每个名称都有自己的地址。因此,除非存在支持上下文,例如,使用静态铸件:

static_cast<int(Foo::*)(const std::string&)>(&Foo::bar)

但是,这要求您知道确切的签名,这与查找返回类型的目标相矛盾。相反,您可以使用decltype指示符和助手declval函数查询返回类型:

std::is_same<decltype(std::declval<Foo&>().bar("")), int>::value