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"
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With