Cla*_*ton 5 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;
}
Run Code Online (Sandbox Code Playgroud)
我需要对未编译的行进行哪些更改,以便可以测试重载方法的返回?
重载的函数名称表示所有重载,每个重载都有其自己的地址。因此,除非存在支持的上下文,否则无法将其解析为一定的重载,例如,使用静态强制类型转换:
static_cast<int(Foo::*)(const std::string&)>(&Foo::bar)
Run Code Online (Sandbox Code Playgroud)
但是,这需要您知道确切的签名,这与查找返回类型的目标相矛盾。相反,您可以使用说明decltype符和帮助declval函数查询返回类型:
std::is_same<decltype(std::declval<Foo&>().bar("")), int>::value
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
315 次 |
| 最近记录: |