有时您希望一个函数返回多个值。一种很常见的方法 在 C++ 中实现这种行为是通过非常量引用传递您的值,并且 在你的函数中分配给他们:
void foo(int & a, int & b)
{
a = 1; b = 2;
}
你会用什么:
int a, b;
foo(a, b);
// do something with a and b
现在我有一个接受这样一个函数的仿函数并且想要转发 将参数设置到另一个返回结果的函数中:
template <typename F, typename G>
struct calc;
template <
typename R, typename ... FArgs,
typename G
>
struct calc<R (FArgs...), G>
{
using f_type = R (*)(FArgs...);
using g_type = G *;
R operator()(f_type f, g_type g) const
{
// I would need to declare each type in FArgs
// dummy:
Args ... args;
// now use the multiple value returning function
g(args...);
// and pass the arguments on
return f(args...);
}
};
这种方法是否有意义,或者我应该使用基于元组的方法 方法?这里有比基于元组的方法更聪明的方法吗?
最佳答案
您可以使用编译时索引:
template< std::size_t... Ns >
struct indices
{
typedef indices< Ns..., sizeof...( Ns ) > next;
};
template< std::size_t N >
struct make_indices
{
typedef typename make_indices< N - 1 >::type::next type;
};
template<>
struct make_indices< 0 >
{
typedef indices<> type;
};
template< typename F, typename G >
struct calc;
template<
typename R, typename ... FArgs,
typename G
>
struct calc< R (FArgs...), G >
{
using f_type = R (*)(FArgs...);
using g_type = G *;
private:
template< std::size_t... Ns >
R impl(f_type f, g_type g, indices< Ns... > ) const
{
std::tuple< FArgs ... > args;
g( std::get< Ns >( args )... );
// alternatively, if g() returns the tuple use:
// auto args = g();
return f( std::get< Ns >( args )... );
}
public:
R operator()(f_type f, g_type g) const
{
return impl( f, g, typename make_indices< sizeof...( FArgs ) >::type() );
}
};
关于c++ - 模板处理函数 "returning"多于一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18723907/