Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic templates and no values

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

In my case I want to make use of an template class eg.

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

Is there a way, that the compiler make an instance with typename T = int for example and if not used or specified, version without typename G?

So that the result looks like:

unicorn <double, int>;

class unicorn {
double value01;
int value02;
};

And without Argument or specified typename G

unicorn <double>

class unicorn {
T value01;
// "not included in this instance"
};
like image 216
dreiti Avatar asked Jun 28 '16 18:06

dreiti


1 Answers

If you have a finite number of use cases and don't want to dive into deep template metaprogramming then you can simply do template 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 an std::tuple might do the trick here. 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 be aware of some things like std::ref and the get<> function with a tuple. You can also access the types of a template pack with some template metaprogramming. I am not explaining that here because it might become a really long answer otherwise, if you would still like me to do so let me know in a comment below and I will try to explain it to you.

like image 61
Curious Avatar answered Oct 24 '22 21:10

Curious