Templates accepting “anything” in C++

后端 未结 4 792
[愿得一人]
[愿得一人] 2021-01-12 05:53

I have a simple template struct associating a string with a value

template struct Field
{
    std::string name; T self;
}

4条回答
  •  悲&欢浪女
    2021-01-12 06:11

    There is no need to use wildcards in C++ templates, since in C++ it always knows the type, and is not "erased" like in Java. To write void foo(Field bar, Field... baz) method(or function) in C++, you would write:

     template
     void foo(Field bar, Field... baz);
    

    Each Field can be a different type. To use the variadic parameters inside the function, you just use baz.... So say you want to call another function:

     template
     void foo(Field bar, Field... baz)
     {
         foo2(baz...);
     }
    

    You can also expand the type with Field..., so if you want to put it in a tuple(you can't put them in array since they can be different types):

     template
     void foo(Field bar, Field... baz)
     {
         std::tuple...> data(baz...);
     }
    

提交回复
热议问题