5

我向现有类添加了一个重载方法,这会导致我们的单元测试中出现编译错误。

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

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

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

4

1 回答 1

6

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

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

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

std::is_same<decltype(std::declval<Foo&>().bar("")), int>::value
于 2017-03-01T12:55:51.973 回答