[英]How to specialize a class template with a 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();
現在我想將此模板專門用於以下 class 模板:
template<char N>
struct B
{
static const bool is_a;
};
template<char N>
const bool B<N>::is_a = N == 'a';
為了A<B<N>>::flag
將使用B<N>::is_a
進行初始化。 即,我想專門針對這種情況使用calc_flag()
方法。 怎么可能做到這一點?
您可以將計算分離到一個實現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();
};
現在你可以專門calc_flag_impl
template<char N>
struct calc_flag_impl<B<N>> {
static bool calc_flag() { return B<N>::is_a; }
};
注意:在為您的類型實例化 class 模板之前,特化必須存在,才能與 static class 變量一起使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.