0

A class template:

template <class X, class Y > class MyTemplate;

I want to partially specialize this class so that when X is a const type, Y is an int and that partial specialization code is chosen if I create an object such as:

MyTemplate<sometype const> var;

whereas if X is a non-const type, Y is a double and that partial specialization code is chosen if I create an object such as:

MyTemplate<sometype> var;

Is this possible in C++11 ? If so, how ? If not, is this possible in C++20 with concepts and requirements ?

  • Is it a requirement that you use partial specialization for this? – cigien Mar 17 '21 at 19:40
  • If you will not give a second type argument, you ought to use a different template name rather than a partial specialization of the first. The specialization is good only if you just want that different default for Y but the user could still specify any type for Y. – JDługosz Mar 17 '21 at 19:42
  • Do you need the Y parameter? Or is it fixed from `X`? – Jarod42 Mar 18 '21 at 08:22

2 Answers2

2

Partial specialization (with possibly enabler):

template <class X, class Y, typename Enabler = void> class MyTemplate;

template <class X>
class MyTemplate<const X, int>
{
// ...
};

template <class X>
class MyTemplate<X, double, std::enable_if_t<!std::is_const_v<X>>>
{
// ...
};

//...

Replace the C++14 X_t<T>/X_v<T> by typename X<T>::type/X<T>::value to be C++11.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
2

You don't really need to use partial specialization for this. You can just write:

template <typename X, 
          typename Y = 
          typename std::conditional<std::is_const<X>::value, int, double>::type> 
class MyTemplate;

Here's a demo

cigien
  • 57,834
  • 11
  • 73
  • 112
  • I still need partial specialization to handle the two code cases of X being a const type or not, but I worked out how to do that. My previous effort only specified X in each partial specialization but when I realized I needed to specify both X and Y in each partial specialization, and not just X, I got everything working correctly. – Edward Diener Mar 17 '21 at 22:13
  • Maybe `template class MyTemplate { using Y = double; /*..*/ };` and specialization `template class MyTemplate { using Y = int; /*..*/ };` is what you want then. – Jarod42 Mar 18 '21 at 08:24
  • The actual situation is much more complicated than just fixing Y from X based on whether X is const or not. I just presented it in that form to understand how I would implement the basics of having two basic diffferent situations for partial specialization, one in which X is non-const and one in which it is const. – Edward Diener Mar 18 '21 at 20:27