Variadic templates and without values

Templates are good for programming functions and template classes, so we can use it to shorten our code and give the compiler some work for us.

In my case, I want to use a template class, for example.

template <typename T, typename G> class unicorn { T value01; G value02; <- not used in ever instance of class unicorn }; 

Is there a way for the compiler to create an instance with a name of type T = int and , if it was not used or not specified , a version without typename G?

To make the result look like this:

 unicorn <double, int>; class unicorn { double value01; int value02; }; 

And without an argument or a given type name G

 unicorn <double> class unicorn { T value01; // "not included in this instance" }; 
+7
c ++ templates dynamic-programming variadic-functions
source share
1 answer

If you have a finite number of use cases and don’t want to dive into the deep metaprogramming of the template, you can just do a specialized specialization

 #include <iostream> using namespace std; template <typename... Args> struct Something; template <typename T> struct Something<T> { T a; }; template <typename T, typename U> struct Something<T, U> { T a; U b; }; int main() { __attribute__((unused)) Something<int> a; __attribute__((unused)) Something<int, double> b; return 0; } 

But for the general case, I think std::tuple can do the trick. Take a look at the following code

 #include <tuple> #include <iostream> using namespace std; template <typename... Args> class Something { std::tuple<Args...> tup; }; int main() { __attribute__((unused)) Something<int> a; __attribute__((unused)) Something<int, double> b; return 0; } 

Of course, you should know about some things like std::ref and get<> with a tuple. You can also access template package types by metaprogramming multiple templates. I am not explaining what is here because it can be a long answer indeed otherwise, if you still want me to do this, let me know in the comment below and I will try to explain it to you.

+5
source share

All Articles