将std :: result_of与重载方法一起使用

时间:2017-03-01 12:23:38

标签: c++ overloading result-of

我在现有类中添加了一个重载方法,现在在单元测试中导致编译错误。

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

#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;
}

我需要对未编译的行进行哪些更改才能测试重载方法的返回值?

1 个答案:

答案 0 :(得分:4)

重载的函数名称表示所有重载,每个重载都有自己的地址。因此,除非存在支持上下文,例如使用静态强制转换,否则无法将其解析为某个过载:

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

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

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