使用模板在头文件初始化静态变量(使用c++11,不支持'inline'方法)
猫base_class.hpp
#include <string>
#ifndef PROGRAM_BASE
#define PROGRAM_BASE
template <typename T>
struct S
{
static std::string s_elfName;
};
template <typename T>
std::string S<T>::s_elfName; //static initialization
class program_base : public S<void>{
public:
static std::string GetElfName() { return S<std::string>::s_elfName; }
bool update_string();
};
#endif
猫base_class.cpp
#include "base_class.hpp"
bool program_base::update_string(){
S<std::string>::s_elfName = "UpdateString";
}
猫read_string.cpp
#include <iostream>
#include "base_class.hpp"
using namespace std;
int main () {
program_base pb; pb.update_string();
cout << program_base::GetElfName() << endl;
}
上面的工作很好,当我尝试在类program_base">
中添加模板时猫base_class.hpp
#include <string>
#ifndef PROGRAM_BASE
#define PROGRAM_BASE
class program_base {
public:
template <typename T>
struct S
{
static std::string s_elfName;
};
template <typename T>
std::string S<T>::s_elfName; //static initialization
static std::string GetElfName() { return S<std::string>::s_elfName; }
bool update_string();
};
#endif
它给出一个错误"错误:成员's_elfName'声明为模板">
为什么我不能在类中声明模板而不是继承它?
如c++标准嵌套类声明中所述:
Member functions and static data members of a nested class can be defined in a namespace scope enclosingthe definition of their class.
[Example:
struct enclose {
struct inner {
static int x;
void f(int i);
};
};
int enclose::inner::x = 1;
void enclose::inner::f(int i) { /* ... */ }
— end example]
如果您将定义从外部类中取出,那么应该没问题:
template <typename T>
std::string program_base::S<T>::s_elfName;
从c++ 17开始,您还可以进行内联静态初始化:
class program_base {
public:
template <typename T>
struct S
{
inline static std::string s_elfName;
};
static std::string GetElfName() { return S<std::string>::s_elfName; }
bool update_string();
};