Instantiate different specialization with the same parameters

94 Views Asked by At

Consider the class below. I would like to use sometimes the first specialization and sometimes the second, but with the same template arguments.

#include <vector>

using namespace std;

// 1
template < typename U, typename V >
class C
{
public: C() {}
};

// 2
template < typename U, typename VT, typename VA >
class C< U, vector<VT, VA> >
{
public: C() {}
};

// 3
template < typename UT, typename UA, typename VT, typename VA >
class C< vector<UT, UA>, vector<VT, VA> >
{
public: C() {}
};

int main() 
{
  C<int, int> a; // 1st
  C<int, vector<int>> b; // 2nd
  C<vector<int>, vector<int>> c; // 3rd
  C<vector<int>, vector<int>> d; // how do I force the instantiation of 2nd?
}
2

There are 2 best solutions below

3
joergbrech On BEST ANSWER

You could define a holder type that is convertible to the held instance

template <typename T>
struct whole
{
    operator T() const { return t; }
    T t;
};

and then change your last line to

 C<whole<vector<int>>, vector<int>> d;

https://godbolt.org/z/479x9qo6v

2
Amir Kirsh On

As already discussed in the comments, if you wish to create different types there must be something different in your definition. It can be either the template arguments, or in a way you can achieve that with different constructor arguments, relying on deduction guides to lead to a specific type (but then without providing the template arguments).

A possible way to achieve what you aim for might be with a factory method that gets your arguments and returns an object of the desired type.