c++ - 确定函数返回类型的最简单方法

标签 c++ function c++17 return-type compile-time

给定一个非常简单但冗长的函数,例如:

int foo(int a, int b, int c, int d) {
    return 1;
}

// using ReturnTypeOfFoo = ???

在编译时确定函数的返回类型(ReturnTypeOfFoo,在本例中为:int)最简单简洁的方法是什么不重复函数的参数类型(仅按名称,因为已知该函数没有任何额外的重载)?

最佳答案

您可以利用 std::function这里将为您提供函数返回类型的别名。这确实需要 C++17 支持,因为它依赖于 class template argument deduction ,但它适用于任何可调用类型:

using ReturnTypeOfFoo = decltype(std::function{foo})::result_type;

我们可以让它更通用一点

template<typename Callable>
using return_type_of_t = 
    typename decltype(std::function{std::declval<Callable>()})::result_type;

然后让你像使用它一样

int foo(int a, int b, int c, int d) {
    return 1;
}

auto bar = [](){ return 1; };

struct baz_ 
{ 
    double operator()(){ return 0; } 
} baz;

using ReturnTypeOfFoo = return_type_of_t<decltype(foo)>;
using ReturnTypeOfBar = return_type_of_t<decltype(bar)>;
using ReturnTypeOfBaz = return_type_of_t<decltype(baz)>;

关于c++ - 确定函数返回类型的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673442/

相关文章:

c++ - 使用我的应用程序控制 Dropbox、Google Drive 和/或 SugarSync。

c++ - C++严格混叠规则使用Qt和QLinkedList编译错误

python - 在 Python 中创建类的开销 : Exact same code using class twice as slow as native DS?

c++ - 采样条件分布OpenMP

c++ - 声明一个可以将lambda用作参数的函数,但该lambda必须能够捕获其他变量

c++ - 将程序参数复制到以空格分隔的 std::string

javascript - AngularJS - 将 this.value 传递给函数

css - 如何一次处理多个 SASS map ?

c++ - `if constexpr`可以用来声明不同类型和init-expr的变量吗

c++ - 比较两个字符时遇到问题