[英]How to specialize a class template with a template?
Consider the class template:考虑 class 模板:
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:现在我想将此模板专门用于以下 class 模板:
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
.为了
A<B<N>>::flag
将使用B<N>::is_a
进行初始化。 Ie, I'd like to specialize the calc_flag()
method for such the case.即,我想专门针对这种情况使用
calc_flag()
方法。 How could this be done?怎么可能做到这一点?
You could separate the calculation to an implementation struct
and only specialize that您可以将计算分离到一个实现
struct
中,并且只专门化它
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
现在你可以专门
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.注意:在为您的类型实例化 class 模板之前,特化必须存在,才能与 static class 变量一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.