简体   繁体   中英

How to specialize a class template with a template?

Consider the class template:

template<typename T>
struct A
{
  T data;

  static const bool flag;
  static bool calc_flag()
  {
    // Default value;
    return false;
  }
};

template<typename T>
const bool A<T>::flag = A<T>::calc_flag();

And now I'd like to specialize this template for the following class template:

template<char N>
struct B
{
  static const bool is_a;
};

template<char N>
const bool B<N>::is_a = N == 'a';

in order to the A<B<N>>::flag will be initialized with the B<N>::is_a . Ie, I'd like to specialize the calc_flag() method for such the case. How could this be done?

You could separate the calculation to an implementation struct and only specialize that

template<class T>
struct calc_flag_impl {
    static bool calc_flag() { return false; }
};

template<typename T>
struct A
{
  T data;

  static const bool flag = calc_flag_impl<T>::calc_flag();
};

Now you can specialize calc_flag_impl

template<char N>
struct calc_flag_impl<B<N>> {
    static bool calc_flag() { return B<N>::is_a; }
};

Note: The specialization must exist prior to instantiation of the class template for your type for it to work with static class variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM