如何确定模板中函数的 return 类型
How to determine the return type of a function in template
我正在尝试编写一个类似于 std::function 的 class,只是为了了解它是如何工作的,但我在确定函数的 return 类型时遇到了问题。
我从这里关于堆栈溢出的一个答案中找到 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 类型之前移动它。
将operator()
中的return ((*fx)(args), ...);
改为return (*fx)(args...);
;也就是说,所有参数都应该传递给 fx
而不是对每个参数多次调用 fx
。
顺便说一句:Return type deduction(自 C++14 起)也值得考虑。例如
template < class... A >
auto operator()(A... args)
{
return (*fx)(args...);
}
您应该在 class 实例化中更改您的模板:
template <typename R, typename ...Args>
class function {
...
R operator()(Args... args){
return fx(...args)
}
}
我正在尝试编写一个类似于 std::function 的 class,只是为了了解它是如何工作的,但我在确定函数的 return 类型时遇到了问题。
我从这里关于堆栈溢出的一个答案中找到 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 类型之前移动它。将
operator()
中的return ((*fx)(args), ...);
改为return (*fx)(args...);
;也就是说,所有参数都应该传递给fx
而不是对每个参数多次调用fx
。
顺便说一句:Return type deduction(自 C++14 起)也值得考虑。例如
template < class... A >
auto operator()(A... args)
{
return (*fx)(args...);
}
您应该在 class 实例化中更改您的模板:
template <typename R, typename ...Args>
class function {
...
R operator()(Args... args){
return fx(...args)
}
}