在嵌套模板专用化期间初始化嵌套模板类的静态成员
Initializing static member of nested templated class during nested template specialization?
这是我的问题:
template<typename T>
class Outer
{
public:
template<typename U>
class Inner
{
private:
static int count;
};
static int code;
void print() const
{
std::cout << "generic";
}
};
template<>
template<>
class Outer<bool>::Inner<bool>
{
static int count;
};
template<>
template<>
int Outer<bool>::Inner<bool>::count = 4; // ERROR
如何正确初始化它?
完全专用的模板实际上不再是模板,因此您的定义应该只是:
int Outer<bool>::Inner<bool>::count = 4;
完整地说,所有定义都已到位,您的代码应如下所示:
template<typename T>
class Outer
{
public:
template<typename U>
class Inner
{
private:
static int count;
};
static int code;
void print() const
{
std::cout << "generic";
}
};
template<typename T>
int Outer<T>::code = 0;
template<typename T>
template<typename U>
int Outer<T>::Inner<U>::count = 0;
template<>
template<>
class Outer<bool>::Inner<bool>
{
static int count;
};
int Outer<bool>::Inner<bool>::count = 4;
若要为每个内部模板类实例获取一个静态成员,可以使用单独的模板类作为替代方法。
template<typename T>
class Outer
{
public:
template<typename U>
class Inner
{
};
};
template <typename T>
struct InnerStatic
{
static int count;
};
template <typename T>
int InnerStatic<T>::count = 4;
int main(int argc, char** argv)
{
std::cout << InnerStatic<Outer<int>::Inner<int>>::count << std::endl;
return 0;
}
相关文章:
- 嵌套在类中时无法设置成员数据
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 如何在 C++ 的外部类构造函数中初始化嵌套类成员
- 当使用嵌套类功能时,使用非静态数据成员的使用无效,但是当函数未固定时可以
- 静态模板成员的嵌套静态模板成员
- 模板类中嵌套类的C 静态成员变量
- 嵌套静态循环由于无法捕获 constexpr 而无法工作
- 如何定义嵌套模板(模板类中的模板类)的静态成员
- 无法在派生类中定义嵌套类成员函数
- 模板类的嵌套类,模板类的静态成员变量
- 初始化嵌套类中的静态常量成员变量
- 在类嵌套静态常量成员变量初始化 Clang vs GCC 哪个编译器是正确的
- 如何使用模板化的外部类单独定义嵌套类成员函数
- 嵌套类中的静态成员是否具有封闭类的静态持续时间
- 在嵌套模板专用化期间初始化嵌套模板类的静态成员
- 嵌套结构:在定义结构指针时使用了无效的非静态成员
- 未定义的引用与嵌套类模板静态常量成员
- 使用非静态数据成员和嵌套类构造函数的类内初始化时出错
- 类型不完整的嵌套静态constexpr.是否有效的c++
- 尝试定义嵌套模板成员函数时"expected expression"