c++ - 如何确定模板中函数的返回类型

标签 c++ templates return-type

我正在尝试编写一个类似于 std::function 的类,只是为了了解它是如何工作的,但我在确定函数的返回类型时遇到了问题。

我找到了 this来自堆栈溢出的答案之一。我正在尝试做类似的事情,但它不起作用,我不知道为什么。

template< class Fx >
class function
{
public:
    function() = default;

    function(Fx* fx)
    {
        this->fx = fx;
    }
        
    template < class... A >
    ReturnType operator()(A... args)
    {
        //return ((*fx)(args), ...); ??
    }

private:
    template<class F>
    struct return_type;

    template< class R, class... A>
    struct return_type<R(*)(A...)>
    {
        using type = R;
    };

    using ReturnType = return_type<Fx>::type;
    Fx* fx;
};


int sum(int a, int b) { return a + b; };

int main()
{
    function<int(int, int)> mysum{ sum };
    mysum(10, 10);
}

在线报错

using ReturnType = return_type<Fx>::type;

不允许使用不完整的类型。为什么不选择专业的?

最佳答案

Fx应该是函数类型,而不是函数指针类型,所以特化应该声明为:

template< class R, class... A>
struct return_type<R(A...)>
{
    using type = R;
};

其他问题:

  1. 更改 using ReturnType = return_type<Fx>::type;using ReturnType = typename return_type<Fx>::type; .

  2. 移动ReturnType的声明(和 return_type 的定义)在将其用作 operator() 的返回类型之前.

  3. 更改 return ((*fx)(args), ...);return (*fx)(args...);operator() ;即所有参数都应该传递给 fx而不是调用 fx每个参数多次。

LIVE

顺便说一句:Return type deduction (C++14 起)也值得考虑。例如

template < class... A >
auto operator()(A... args)
{
    return (*fx)(args...);
}

LIVE

关于c++ - 如何确定模板中函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70883061/

相关文章:

c++ - 在链表中存储数组元素

c++ - 如何设置动态分配数组的内容?

java - 为什么我不需要处理页面对象的返回类型?

postgresql - 从 PostgreSQL 中的函数返回表类型

c++ - 既是基类又可直接使用的类模板

c - char* 作为函数的返回类型有什么作用或意义?

c++ - 用户自定义bool转换的优先级

c++ - Visual Studio 2010 - 源代码从项目文件夹中消失

c++ - 使用默认参数的构造函数模板实例化

c++ - 为什么 `void* = 0` 和 `void* = nullptr` 会有所不同?