c++ - 如何在派生类中初始化基类静态内联数据成员?

标签 c++ templates static c++17 class-template

假设我正在上课

#include<iostream>
#include<string>

template<typename CharT>
class base
{
   //.....
public:
   using string_type = std::basic_string<CharT>;
   static inline string_type var;
   //.....
};

class derived : public base<char>
{
private:
   using base<char>::var;
public:
   static base<char>::string_type get()
   {
      return var;
   }
};

//template<>
//base<char>::string_type base<char>::var = "Value";

int main()
{
   std::cout << derived::get();
}

base 类接受 char 类型并为该类创建一个字符串类型,但我想在类中使用该 strng_type 字符串, 所以我创建了一个必须由类的用户设置的 static string_type 变量。

char 的值为 "Value"wchar_t 的值为 L"Value"。所以我想通过继承指定类型 (char) 的类来对用户隐藏 var 现在如何初始化 var

我已经尝试通过删除 inline 并取消注释它工作的模板,但是有一种方法可以初始化 inline static 基类变量。

  1. 如何初始化基类内联静态数据成员?
  2. 这样做是个好主意吗?

最佳答案

How to init base class inline static data member?

删除内联,你应该是able to initialize the var

template<typename CharT>
class base
{
public:
   using string_type = std::basic_string<CharT>;
   static string_type var;
   // ^^^^^^^^^^^^^^^^^^^
};

template<>
base<char>::string_type base<char>::var = "Value";

template<>
base<wchar_t>::string_type base<wchar_t>::var = L"Value";

It is a good idea doing like this?

不确定设计。因为你在这里提到的

"I want to hide the var from a user by inheriting the class in specified type(char) [...]"

看起来,还是可以通过

std::cout << base<char>::var;

关于c++ - 如何在派生类中初始化基类静态内联数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63223162/

相关文章:

c++ - 在 Eclipse 中对 C++ 方法进行排序/按字母顺序排列(不在大纲中,在代码中)

c# - 基类和派生类中的静态字段

java - 静态变量和非静态变量可以同名

java - 使用静态类来表示不同形式的货币

C++成员初始化列表问题

C++ 迭代器随机失效

c++ - 我的程序无法正确计算单词或字符的行数?

templates - Grails gsp模板。从gsp传递参数并接受其on模板

c++ - 在C++中将函数返回类型指定为模板参数

templates - 如何为登录页面定义一个模板/ View /任何内容,但为其他页面定义默认模板/ View /任何内容