c++ - 模板处理函数 "returning"多于一个值

标签 c++ templates c++11

有时您希望一个函数返回多个值。一种很常见的方法 在 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/

相关文章:

c++ - Simulink S-Function Builder仅允许一维和二维尺寸。如何为RGB图像选择3-D?

c++ - 在没有模板特化的情况下更改函数的返回类型。 C++

c++ - 模板元编程积分特化

c++ - 函数的引用限定符有什么实际用例吗?

c++ - 第一个参数没有从 'A' 到 'A &&' 的已知转换

c++ - 读入 ascii 扩展字符

C++ 泛型链表独立类

c++ - WinHttp C++ 中的 POST 请求

c++ - 转发声明的枚举,.h 中的默认值

python 数据结构 : map<string, vector<int>>