I don’t understand why if I initialize this template variable globally, like this:
template <class T> struct null_string { static const std::string value; };
template<class T> const std::string null_string<T>::value = "";
template<class T> std::string const null_str = null_string<const T&>::value;
it works, but if I try to initialize it inside a class, like this:
class foo
{
template <class T> struct null_string { static const std::string value; };
template<class T> const std::string null_string<T>::value = "";
template<class T> std::string const null_str = null_string<const T&>::value;
};
it gave me an error:
prove.cpp:8:65: error: invalid use of qualified-name ‘foo::null_string<T>::value’
8 | template<class T> const std::string null_string<T>::value = "";
| ^~
prove.cpp:11:78: error: data member ‘null_str’ cannot be a member template
11 | template<class T> std::string const null_str = null_string<const T&>::value;
|
Do you know why?
>Solution :
Add missing static. Then, either move variable definitions to namespace scope:
class foo
{
template <class T> struct null_string { static const std::string value; };
template <class T> static std::string const null_str;
};
template <class T> const std::string foo::null_string<T>::value = "";
template <class T> std::string const foo::null_str = foo::null_string<const T&>::value;
Or make them inline:
class foo
{
template <class T> struct null_string { inline static const std::string value = ""; };
template <class T> inline static const std::string null_str = foo::null_string<const T&>::value;
};