如何在 C++ 中获取 return 类型的重载方法?
How to get return type of overloaded method in C++?
我在某处有一个结构:
struct A {
ComplicatedType1 f();
ComplicatedType2 f(int);
};
我想使用编译时助手获取 return 类型的 f()
。我正在尝试 std::result_of<>
:
using Type = std::result_of<decltype(&A::f)()>::type;
但是编译器给我一个合理的错误:"reference to overloaded function could not be resolved".
所以我去 SO 并看到 this 已接受和赞成的答案,建议做一个 static_cast<ComplicatedType1 (A::*)()>(&A::f)
- 但我现在没有 ComplicatedType1
。我陷入了递归。
如何用最少的代码在我的 using
表达式中获取 ComplicatedType1
?
的工作
#include <iostream>
#include <type_traits>
#include <utility>
struct ComplicatedType1 {};
struct ComplicatedType2 {};
struct A {
ComplicatedType1 f();
ComplicatedType2 f(int);
};
int main()
{
using Type = decltype(std::declval<A>().f());
static_assert(std::is_same<Type,ComplicatedType1>::value,"Oops");
}
编辑:更改为在 Coliru
上获取 return 类型的 f()(而不是 f(int))和 c++11(而不是 c++14)
我在某处有一个结构:
struct A {
ComplicatedType1 f();
ComplicatedType2 f(int);
};
我想使用编译时助手获取 return 类型的 f()
。我正在尝试 std::result_of<>
:
using Type = std::result_of<decltype(&A::f)()>::type;
但是编译器给我一个合理的错误:"reference to overloaded function could not be resolved".
所以我去 SO 并看到 this 已接受和赞成的答案,建议做一个 static_cast<ComplicatedType1 (A::*)()>(&A::f)
- 但我现在没有 ComplicatedType1
。我陷入了递归。
如何用最少的代码在我的 using
表达式中获取 ComplicatedType1
?
#include <iostream>
#include <type_traits>
#include <utility>
struct ComplicatedType1 {};
struct ComplicatedType2 {};
struct A {
ComplicatedType1 f();
ComplicatedType2 f(int);
};
int main()
{
using Type = decltype(std::declval<A>().f());
static_assert(std::is_same<Type,ComplicatedType1>::value,"Oops");
}
编辑:更改为在 Coliru
上获取 return 类型的 f()(而不是 f(int))和 c++11(而不是 c++14)