【问题标题】:How to init base class staic inline data member in derived class?如何在派生类中初始化基类静态内联数据成员?
【发布时间】:2020-08-03 03:03:17
【问题描述】:

假设我正在上课

#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. 这样做是个好主意吗?

【问题讨论】:

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


    【解决方案1】:

    如何初始化基类内联静态数据成员?

    删除inline,你应该是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";
    

    这样做是个好主意吗?

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

    "我想通过继承类来向用户隐藏var 指定类型(char) [...]"

    看起来,它仍然可以通过

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

    【讨论】:

    • 感谢您的回答,我将在基类中将 public 更改为 protected :-)
    猜你喜欢
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2019-01-25
    • 1970-01-01
    • 2017-08-30
    • 2023-03-31
    相关资源
    最近更新 更多