如何判断重载函数的返回类型?

Ale*_*sky 0 c++

在下面的代码中,如何f在不实例化Aand的情况下确定两个重载的返回类型B

class A
{
public:

    A(std::string k) : key(k)
    {
    }

private:

    std::string key;
};

class B
{
public:

    B(int k) : key(k)
    {
    }

private:

    int key;
};

int f(const A&);
std::string f(const B&);

// It is possible to determine the return types as follows:
using a_return_type = decltype(f(A{ "" }));
using b_return_type = decltype(f(B{0}));
Run Code Online (Sandbox Code Playgroud)

伪代码解决方案:

using a_return_type = std::invoke_result_t<f, A>;
using b_return_type = std::invoke_result_t<f, B>;
Run Code Online (Sandbox Code Playgroud)

编辑1

我需要一个没有A{ "" }和的解决方案B{0}。假设我不知道AB构造函数是什么。

编辑2

至少这是可能的,代码如下:

A* p_a = nullptr;
B* p_b = nullptr;
using a_return_type = decltype(f(*p_a));
using b_return_type = decltype(f(*p_b));
Run Code Online (Sandbox Code Playgroud)

但显然这不是最好的编码风格。

或者

using a_return_type = decltype(f(*static_cast<A*>(nullptr)));
using b_return_type = decltype(f(*static_cast<B*>(nullptr)));
Run Code Online (Sandbox Code Playgroud)

Art*_*yer 6

您想要一个Aor类型的对象B在未计算的上下文中,但实际上不知道如何构造Aor B。这正是目的std::declval

using a_return_type = decltype(f(std::declval<A>()));
using b_return_type = decltype(f(std::declval<B>()));
Run Code Online (Sandbox Code Playgroud)