camino camino - 21 days ago 7
C++ Question

Why class specialization from template<typename T1, typename T2> to template<typename T1, int i> not supported

I am wondering why class specialization from

template<typename T1, typename T2>
to
template<typename T1, int i>
is not supported.

For example:

template<typename T1, typename T2>
struct B{};

template<typename T1>
struct B<T1, T1>{}; //ok

template<typename T1>
struct B<T1, int>{}; //ok

template<typename T1,int i>
struct B<T1,i>{}; //error: expected a type, got 'i'

template<typename T1,constexpr int i>
struct B<T1,i>{}; //error: expected a type, got 'i'

Answer

Your primary template expects a type parameter, but i is not a type, it is a non-type argument. int is a type.

You can use std::integral_constant to bind them somehow:

template<typename T1, int i>
struct B<T1, std::integral_constant<int, i>>{};

It is not exactly the same thing, but a using declaration can help to work around it:

template<typename T1, int i>
using BT = struct B<T1, std::integral_constant<int, i>>;