Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a template with variable number of type parameters?

In our codebase we use std::variant<std::shared_ptr<SomeClass>, ...> a lot.

That obviously requires a lot of writing. How to make a template?

template <class... T>
using VarSP = std::variant<std::shared_ptr<???>>;

Where should T go in the above snippet? The desired behavior should be:

VarSP<Foo, Bar, Baz> // std::variant<std::shared_ptr<Foo>, std::shared_ptr<Bar>, std::shared_ptr<Baz>>
like image 351
Nurbol Alpysbayev Avatar asked Sep 02 '19 09:09

Nurbol Alpysbayev


People also ask

Which template can have multiple parameters?

C++ Templates: Templates with Multiple Parameters | C++ Tutorials for Beginners #65.

What is template type parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Can we use non-type parameters as arguments template?

Non-type template arguments are normally used to initialize a class or to specify the sizes of class members. For non-type integral arguments, the instance argument matches the corresponding template parameter as long as the instance argument has a value and sign appropriate to the parameter type.

How do you declare a template variable in C++?

A variable template may be introduced by a template declaration at namespace scope, where variable-declaration declares a variable. When used at class scope, variable template declares a static data member template.


1 Answers

template <typename... T>
using VarSP = std::variant<std::shared_ptr<T>...>;
like image 177
user7860670 Avatar answered Sep 20 '22 07:09

user7860670