是否有可能在不传递参数的情况下获得函数的返回类型?
Is it possible to get the return type of a function without passing arguments to it?
显然,您可以使用decltype(foo())获得函数的返回类型,但如果foo接受的参数不起作用,则必须传递一些虚拟参数给foo以使其工作。但是,有没有一种方法可以在不传递任何参数的情况下获得函数的返回类型?
假设返回类型不依赖于参数类型(在这种情况下,您应该使用类似std::result_of
的东西,但您必须提供这些参数的类型),您可以编写一个简单的类型trait,使您可以从函数类型推断返回类型:
#include <type_traits>
template<typename T>
struct return_type;
template<typename R, typename... Args>
struct return_type<R(Args...)>
{
using type = R;
};
int foo(double, int);
int main()
{
using return_of_foo = return_type<decltype(foo)>::type;
static_assert(std::is_same<return_of_foo, int>::value, "!");
}
c++ 11提供std::result_of
在函数接受参数的情况下,您可以使用std::declval
提供"假"参数。
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 在不传递参数数量且只有3个点的情况下,如何使用变差函数
- 在这种情况下,java对象是否可以调用本机函数
- 这个c++代码是如何在没有定义函数的情况下运行的
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 如何在没有函数的情况下编写此代码并使C++更简单?
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- A类的定义需要B类的定义,如何在不公开B的定义的情况下公开A的公共函数?
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 有没有办法在不使用 #ifdef 的情况下不编译发布版本中的单元测试函数体?
- C++ strcpy 函数在少数主要情况下失败
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何在没有复制构造函数的情况下为地图设置值?
- 在这种情况下,如何传递成员函数而不是函数?
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 在没有默认构造函数的情况下创建的派生对象
- 在双重继承的情况下如何处理非标准构造函数