我正在尝试确定重载成员函数的返回类型,以便稍后在我的函数模板中使用该类型(参见下面的示例)。无法弄清楚如何使用 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)
正确推导了 double
和 int *
.
旁注:模板函数的整个主体可以简化为 return X().f(arg);
。
关于c++ - 获取重载成员函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27969105/