2017-03-01 49 views
4

我在现有类中添加了重载方法,现在在我们的单元测试中会导致编译错误。在重载方法中使用std :: 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; 
} 

什么样的变化,我需要作出不编译,这样我可以测试一个重载的方法的返回行?

+2

http://stackoverflow.com/q/22291737/1460794 – wally

+5

'的std :: is_same decltype符和一个辅助declval功能查询返回类型().bar(“”)),int> :: value' –

+0

@Muscampester谢谢,接受的答案帮助我理解了Piotr的评论 – camelCase

回答

4

重载函数名称代表所有重载,每个重载都有自己的地址。因此,除非存在支撑情况下,例如,它不能被解析到一定的超载,静态管型:

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

然而,这需要你知道确切的签名,这与寻找的目标返回类型。

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