【问题标题】:Using std::result_of with an overloaded method将 std::result_of 与重载方法一起使用
【发布时间】:2017-03-01 12:23:38
【问题描述】:

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

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

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

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

【问题讨论】:

标签: c++ overloading result-of


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-12
    • 2020-04-20
    • 1970-01-01
    • 2015-06-21
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多