简体   繁体   English

如何在C ++中传递参数包?

[英]How to pass around parameter packs in C++?

Consider the following example: 请考虑以下示例:

template <class T> class method_traits;
template <class T, class Ret, class... Arg> class method_traits<Ret(T::*)(Arg...)> {
public:
    using type = Arg; // this does not work
};

template <class T> using argument_types = typename method_traits<T>::type;

template <class T> class Node {
    T t;
public:
    Node(Input<argument_types<decltype(&T::process)>>... inputs) { // how do I make this work?
        ...
    }
};

The arguments of the constructor of Node<T> depend on the arguments of the method T::process . Node<T>的构造函数的参数取决于方法T::process的参数。 So if a type T has a method process of the signature float process(float a, int b) the signature of the constructor of Node<T> should look like this: Node(Input<float> a, Input<int> b) . 因此,如果一个类型T有一个方法process该签名的float process(float a, int b)的构造方法的签名Node<T>应该是这样的: Node(Input<float> a, Input<int> b)

How do I extract the parameter pack from T::process to use it on the constructor of Node ? 如何从T::process提取参数包以在Node的构造函数上使用它?

Obviously you can't save a list of types in this way 显然,您无法以这种方式保存类型列表

    using type = Arg;

where Arg is a variadic list of types. 其中Arg是一个可变的类型列表。

But you can save they in a type container and std::tuple can do this works too. 但是你可以将它们保存在一个类型容器中, std::tuple也可以这样做。 So I suggest to modify the method_traits specialization as follows 所以我建议修改method_traits ,如下所示

template <typename T>
struct method_traits;

template <typename T, typename Ret, typename... Args>
struct method_traits<Ret(T::*)(Args...)>
 { using tTypes = std::tuple<Args...>; };

and rewrite argument_types to intercept the std::tuple 并重写argument_types来拦截std::tuple

template <typename T>
using tTypes = typename method_traits<T>::tTypes;

Now you can use the default template value and partial specialization trick defining node 现在您可以使用默认模板值和部分特化技巧定义节点

template <typename T, typename TArgs = tTypes<decltype(&T::process)>>
struct Node;

In this way, instantiating a Node<T> object, you effectively get a Node<T, tTypes<decltype(&T::process)> that is a Node<T, std::tuple<Args...>> with the wanted Args... . 通过这种方式,实例化Node<T>对象,您可以有效地获得Node<T, tTypes<decltype(&T::process)> ,这是一个Node<T, std::tuple<Args...>>想要Args...

So you can simply define the following partial specialization of Node as follows 因此,您可以简单地定义Node的以下部分特化,如下所示

template <typename T, typename ... Args>
struct Node<T, std::tuple<Args...>>
 {
   T t;

   Node (Input<Args> ... inputs)
    { /* do something */ }
 };

The following is a full working example 以下是一个完整的工作示例

#include <tuple>
#include <type_traits>

template <typename T>
struct tWrapper
 { using type = T; };

template <typename T>
using Input = typename tWrapper<T>::type;

template <typename T>
struct method_traits;

template <typename T, typename Ret, typename... Args>
struct method_traits<Ret(T::*)(Args...)>
 { using tTypes = std::tuple<Args...>; };

template <typename T>
using tTypes = typename method_traits<T>::tTypes;

template <typename T, typename TArgs = tTypes<decltype(&T::process)>>
struct Node;

template <typename T, typename ... Args>
struct Node<T, std::tuple<Args...>>
 {
   T t;

   Node (Input<Args> ... inputs)
    { /* do something */ }
 };

struct foo
 {
   float process (float a, int b)
    { return a+b; }
 };

int main ()
 {
   Node<foo> nf(1.0f, 2);
 }

-- EDIT -- - 编辑 -

As pointed by Julius (and the OP themselves) this solution require an additional template type with a default template value. 正如Julius(以及OP本身)所指出的,此解决方案需要一个具有默认模板值的附加模板类型。

In this simplified case isn't a problem but I can imagine circumstances where this additional template argument can't be added (by example: if Node receive a variadic list of template arguments). 在这个简化的情况下不是问题,但我可以想象无法添加此附加模板参数的情况(例如:如果Node接收模板参数的可变参数列表)。

In those cases, Julius propose a way that complicate a little the solution but permit to avoid the additional template parameter for Node : to add a template base class, that receive the TArgs arguments, and to works with constructor inheritance. 在这些情况下,Julius提出了一种使解决方案复杂化但允许避免Node的附加模板参数的方法:添加模板基类,接收TArgs参数,以及使用构造函数继承。

That is: defining a NodeBase as follows 即:定义NodeBase如下

template <typename, typename>
struct NodeBase;

template <typename T, typename ... Args>
struct NodeBase<T, std::tuple<Args...>>
 {
   T t;

   NodeBase (Input<Args> ...)
    { /* do something */ }
 };

there is no need for an additional template parameter, for Node , that can simply written as 对于Node ,不需要额外的模板参数,可以简单地写为

template <typename T>
struct Node
   : public NodeBase<T, tTypes<decltype(&T::process)>>
 { using NodeBase<T, tTypes<decltype(&T::process)>>::NodeBase; };

Julius, following this idea, prepared a solution that (IMHO) is even better and interesting. 朱利叶斯遵循这个想法,准备了一个解决方案 ,(恕我直言)更好,更有趣。

Here is one example in C++11 (thanks to max66's comment) based on max66's great answer . 以下是基于max66的优秀答案的 C ++ 11中的一个示例(感谢max66的评论)。 The differences here: 这里的差异:

  • no additional template argument for Node (instead, using a base class and constructor inheritance) Node没有额外的模板参数(相反,使用基类和构造函数继承)
  • the desired arguments are obtained with a slightly different style than shown in the question 获得所需的参数,其风格与问题中显示的略有不同
    • adding overloads for qualified member functions is simple 为合格的成员函数添加重载很简单
    • references are not a problem (as far as I can tell; see example below printing 42 ) 引用不是问题(据我所知;见下面的例子,打印42

http://coliru.stacked-crooked.com/a/53c23e1e9774490c http://coliru.stacked-crooked.com/a/53c23e1e9774490c

#include <iostream>

template<class... Ts> struct Types {};

template<class R, class C, class... Args>
constexpr Types<Args...> get_argtypes_of(R (C::*)(Args...)) {
    return Types<Args...>{};
}

template<class R, class C, class... Args>
constexpr Types<Args...> get_argtypes_of(R (C::*)(Args...) const) {
    return Types<Args...>{};
}

template<class T, class ConstructorArgs>
struct NodeImpl;

template<class T, class Arg0, class... Args>
struct NodeImpl<T, Types<Arg0, Args...>> {
  NodeImpl(Arg0 v0, Args...) {
    v0 = typename std::decay<Arg0>::type(42);
    (void)v0;
  }
};

template<class T>
struct Node
  : NodeImpl<T, decltype(get_argtypes_of(&T::process))>
{
  using ConstructorArgs = decltype(get_argtypes_of(&T::process));
  using NodeImpl<T, ConstructorArgs>::NodeImpl;
};

struct Foo {
    void process(int, char, unsigned) const {}
};

struct Bar {
    void process(double&) {}
};

int main() {
    Node<Foo> foo_node{4, 'c', 8u};

    double reftest = 2.0;
    Node<Bar> bar_node{reftest};
    std::cout << reftest << std::endl;
}

Using perfect forwarding ( live ): 使用完美转发( 直播 ):

template<typename... Args>
Node(Args&&... args) {
    process(std::forward<Args>(args)...);
}

Here is a solution using C++14. 这是使用C ++ 14的解决方案。 (Note: I have only tested it in clang, though): (注意:我只在clang中测试过它):

#include <string>
#include <utility>

struct Foo {
    void process(int, std::string);
};

template <typename T>
struct Input { };

template <std::size_t N, typename T, typename ...Types>
struct Extract_type {
    using type = typename Extract_type<N - 1, Types...>::type;
};

template <typename T, typename ...Types>
struct Extract_type<0, T, Types...> {
    using type = T;
};

template <typename T, std::size_t N, typename R, typename ...Args>
typename Extract_type<N, Args...>::type extract(R (T::*)(Args...));

template <typename T, typename R, typename ...Args>
std::integral_constant<std::size_t, sizeof...(Args)> num_args(R (T::*)(Args...));

template <typename T>
struct Node {
    template <typename ...Args>
    Node(Input<Args>&&... args) 
    : Node(std::make_index_sequence<decltype(num_args<T>(&T::process))::value>{ }, std::forward<Input<Args>>(args)...)
    {}

    template <std::size_t ...Indices>
    Node(std::index_sequence<Indices...>, Input<decltype(extract<T, Indices>(&T::process))>...) {}
};


int main() {
    Node<Foo> b{ Input<int>{ }, Input<std::string>{ } };
}

http://coliru.stacked-crooked.com/a/da7670f80a229931 http://coliru.stacked-crooked.com/a/da7670f80a229931

How about using private inheritance and CRTP? 如何使用私有继承和CRTP?

#include <tuple>
#include <iostream>

template <typename Method> struct method_traits;

template <typename T, typename Ret, typename... Args>
struct method_traits<Ret(T::*)(Args...)> {
public:
    using parameter_pack = std::tuple<Args...>;
};

template <typename Derived, typename Tuple> struct Base;

template <typename Derived, typename... Ts>
struct Base<Derived, std::tuple<Ts...>> {
    void execute_constructor(Ts&&... ts) { 
        Derived* d = static_cast<Derived*>(this);
        d->t.process(std::forward<Ts>(ts)...);
        d->num = sizeof...(Ts);
    }
    virtual ~Base() = default;
};

template <typename T, typename... Rest>
class Node : Base<Node<T, Rest...>, typename method_traits<decltype(&T::process)>::parameter_pack> {
    T t;
    int num;
public:
    using Base = Base<Node<T, Rest...>, typename method_traits<decltype(&T::process)>::parameter_pack>;
    friend Base;  // So that Base can do whatever it needs to Node<T, Rest...>'s data members.
    template <typename... Ts>
    Node (Ts&&... ts) {
        Base::execute_constructor(std::forward<Ts>(ts)...);
        std::cout << "num = " << num << '\n';
    }
};

struct foo {
    void process(int a, char c, bool b) {
        std::cout << "foo(" << a << ", " << c << ", " << std::boolalpha << b << ") carried out.\n";
    }   
};

int main() {
    Node<foo> n(5, 'a', true);
    std::cin.get();
}

Output: 输出:

foo(5, a, true) carried out.
num = 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM