Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to initialize a template variable inside a class, why?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading