模板处理函数“返回”多个值

时间:2013-09-10 16:08:01

标签: c++ templates c++11

有时您希望函数返回多个值。一种非常常见的方式 在C ++中实现这样的行为是通过非const引用传递你的值 在你的函数中分配给他们:

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...);
    }
};

这种方法是否有意义,或者我应该使用基于元组的方法 进场?这里有比基于元组的方法更聪明的东西吗?

2 个答案:

答案 0 :(得分:2)

您可以使用编译时索引:

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() );
   }
};

答案 1 :(得分:1)

当接受我们正在更改fg的签名以使用std::tuple的事实时,此问题的答案变得微不足道:

template <typename F, typename G> struct calc;

template <typename R, typename ... Args>
struct calc<R (std::tuple<Args...> const &), std::tuple<Args...> ()>
{
    using f_type = R (*)(std::tuple<Args...> const &);
    using g_type = std::tuple<Args...> (*)();

    R operator()(f_type f, g_type g) const
    {
        return f(g());
    }
};

这是一个简单的例子:

int sum(std::tuple<int, int> const & t) { return std::get<0>(t) + std::get<1>(t); }
std::tuple<int, int> gen() { return std::make_tuple<int, int>(1, 2); }

auto x = calc<decltype(sum), decltype(gen)>()(&sum, &gen);

然而,此解决方案的局限性很明显:您必须编写自己的函数。使用此方法无法使用std::pow作为f这样的内容。