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.
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
varfrom a user by inheriting the class in specified type(char) [...]"
It looks like, it is still accessible via
std::cout << base<char>::var;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With