Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to init base class staic inline data member in derived class?

Say I am having a class like

#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 class accept a char type and creates a string type for that class, but I want to use that strng_type string in the class, so I created a static string_type variable that has to set by the user of the class.

For char the value is "Value" and For wchar_t value is L"Value". so I want to hide the var from a user by inheriting the class in specified type(char) now how to init that var.

I have tried by removing the inline and uncomment the template it works but there is a way to init inline static base class variable.

  1. How to init base class inline static data member?
  2. It is a good idea doing this?
like image 780
srilakshmikanthanp Avatar asked Jan 25 '26 23:01

srilakshmikanthanp


1 Answers

How to init base class inline static data member?

Remove the inline and you should be 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?

Not sure about the design. Because what you mentioned here

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

It looks like, it is still accessible via

std::cout << base<char>::var;
like image 122
JeJo Avatar answered Jan 28 '26 15:01

JeJo