Search code examples
c++templatesspecialization

Instantiate different specialization with the same parameters


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?
}

Solution

  • 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