Using std :: result_of with overloaded method

I added an overloaded method to an existing class that now causes a compilation error in our unit tests.

I replicated the problem with the following code:

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

What changes do I need to make to a line that does not compile so that I can check the return of the overloaded method?

+4
source share
1 answer

An overloaded function name represents all overloads, each of which has its own address. Thus, it cannot be allowed to a certain overload if there is no supporting context, for example, static casting is used:

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

, , , , . , decltype declval:

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

Source: https://habr.com/ru/post/1671140/


All Articles