Reputation: 719
I'd like to create a template class that takes as many parameters as are the times it has been called in the program. Its usage should be the following:
template<typename... Ts>
class A
{
std::variant<Ts> v;
};
If in the rest of the program I'd instantiate
A<int> a;
A<double> b;
Then I'd like if the compiler could instantiate a class of this kind:
class A
{
std::variant<int, double> v;
};
Instead if in another program I'd instantiate:
A<std::vector<int>> c;
A<std::list<float>> d;
A<char> e;
Then the compiler could instantiate:
class A
{
std::variant<std::vector<int>, std::list<float>, char> v;
};
The heart of the question is that I'm too lazy to change the type parameters of A
every time I use it with different types. So I'd like if the compiler could take count of all the usages of A
and create an appropriate "union" of them.
I think that it'll be possible with "concepts", but is there a feasible solution in the meanwhile?
Upvotes: 3
Views: 100
Reputation: 474326
What you want is not possible. A single translation unit cannot possibly know how the entire program instantiates a template. Code in one translation unit cannot accidentally affect the compilation of code in another translation unit.
Indeed, thanks to dynamic loading of code, it's impossible for even a linked program to know what happens throughout the entire program, since the entire program is not visible to the compilation process.
Just get used to keeping that data structure in sync with your code. Indeed, that is something you can detect: when you instantiate A
with a particular type, you can inspect the corresponding variant
to see if the given type is in that type list. If it isn't, you can issue a compile error.
Alternatively re-evaluate your design so that an "omni-variant" of this sort is not necessary. Or just use any
if that's appropriate to your use case.
I think that it'll be possible with "concepts"
No, it won't.
Upvotes: 6