我正在尝试编写一个类似于 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;
};
其他问题:
更改
using ReturnType = return_type<Fx>::type;
至using ReturnType = typename return_type<Fx>::type;
.移动
ReturnType
的声明(和return_type
的定义)在将其用作operator()
的返回类型之前.更改
return ((*fx)(args), ...);
至return (*fx)(args...);
在operator()
;即所有参数都应该传递给fx
而不是调用fx
每个参数多次。
顺便说一句:Return type deduction (C++14 起)也值得考虑。例如
template < class... A >
auto operator()(A... args)
{
return (*fx)(args...);
}
关于c++ - 如何确定模板中函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70883061/