繁体   English   中英

具有本身的静态const成员实例的C ++模板类

[英]C++ Template class with a static const member instance of itself

模板类的静态const成员应按以下方式初始化:

template <typename T>
class TypeA{
public:
   static const int INSTANCE = 1;
};

如果我们要使用TypeA类而不是int的实例,什么是正确的语法?

例如:

#include <iostream>

template <typename T>
class TypeA{
public:
    T mData;
    TypeA(T data) : mData(data){}

    static const TypeA<T> INSTANCE = TypeA<T>(1);
};


int main(int argc, char **argv){
    std::cout << TypeA<int>::INSTANCE.mData << std::endl;
}

产生错误(gcc):

main.cpp||In instantiation of 'class TypeA<int>':|
main.cpp|14|required from here|
main.cpp|9|error: in-class initialization of static data member 'const TypeA<int> TypeA<int>::INSTANCE' of incomplete type|
main.cpp||In instantiation of 'const TypeA<int> TypeA<int>::INSTANCE':|
main.cpp|14|required from here|
main.cpp|9|error: in-class initialization of static data member 'const TypeA<int> TypeA<int>::INSTANCE' of non-literal type|
main.cpp|9|error: non-constant in-class initialization invalid for static member 'TypeA<int>::INSTANCE'|
main.cpp|9|error: (an out of class initialization is required)|
main.cpp|9|error: 'TypeA<int>::INSTANCE' cannot be initialized by a non-constant expression when being declared|
||=== Build finished: 5 errors, 4 warnings (0 minutes, 0 seconds) ===|

只需遵循编译器为您提供的指示即可:

main.cpp | 9 |错误:类型不完整的静态数据成员'const TypeA TypeA :: INSTANCE'的类内初始化|

您无法初始化尚未完全声明的类型。 因此,您必须将初始化移出类声明:

#include <iostream>

template <typename T>
class TypeA{
public:
    T mData;
    TypeA(T data) : mData(data){}

    static const TypeA<T> INSTANCE;
};

template <typename T>
const TypeA<T> TypeA<T>::INSTANCE = TypeA<T>(1);

int main(int argc, char **argv){
    std::cout << TypeA<int>::INSTANCE.mData << std::endl;
}

您不能在类内部初始化INSTANCE。 您需要稍后再做。

#include <iostream>
template <typename T>
class TypeA{
public:
    T mData;
    TypeA(T data) : mData(data){}
    static const TypeA<T> INSTANCE;
};
template <typename T> const TypeA<T> TypeA<T>::INSTANCE=TypeA<T>(1);

int main(int argc, char **argv){
    std::cout << TypeA<int>::INSTANCE.mData << std::endl;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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