c++ - 获取重载成员函数的返回类型

标签 c++ templates overloading return-type

我正在尝试确定重载成员函数的返回类型,以便稍后在我的函数模板中使用该类型(参见下面的示例)。无法弄清楚如何使用 C++11 模板机制来做到这一点(不修改下面代码中结构 A 和 B 的定义)。这是否可行(一般在 C++11 中,特别是在 MSVS2013 中)以及如何实现?

struct A{};
struct B{};

struct X
{
    double f(A&);
    int* f(B&);
};

template<typename T, typename R = /*??? what X::f(T) returns ???*/>
R ff(T& arg)
{
    X x;
    R r = x.f(arg); // preferably if I can create local variables of type R here
    return r;
}

int main()
{
    A a; ff(a);
    B b; ff(b);
}

最佳答案

为此,您可以使用 decltype(),使用 std::declval 来模拟创建方法调用表达式所需的类型的值:

typename R = decltype(std::declval<X>().f(std::declval<T&>()))

Here is a demo输出 R 的类型 ID;您可以看到它分别为 ff(a)ff(b) 正确推导了 doubleint * .


旁注:模板函数的整个主体可以简化为 return X().f(arg);

关于c++ - 获取重载成员函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27969105/

相关文章:

c++ - CppCMS-嵌入式 404

templates - 如何在 Yesod 中导入莎士比亚模板?

c++ - C++ 中的自由定理 : are templates inherently ignorant and neutral with their objects of unknown types?

c++ - 为什么这是允许的?

c# - 我怎样才能在c#中拥有一种虚拟静态成员

c++ - 将结构对象作为参数传递给 C++ 中的函数是一种好习惯吗?

c++ - 将新方法的方法指针传递给基类

c++ - 如何从另一个类中的私有(private)指针指向的类中获取私有(private)信息?

C++ 模板特化

c# - 使 C# webmethod 的参数可选的最佳方法