0

So if I want to specialise:

template<typename T>
class my_class{
       private:
          static const std::string my_string;
        };

The only way I was able to do it was via

template<> const std::string my_class<some_type>::my_string = "the string";

Let's say I have a bunch of private static members and a bunch of specialisations.

Is there a cleaner way to do this? closer to:

my_class<some_type>::my_string = "the string";
ildjarn
  • 62,044
  • 9
  • 127
  • 211
xvan
  • 4,554
  • 1
  • 22
  • 37

1 Answers1

1

One approach is tag dispatching.

template<class T> struct tag_t{using type=T;};
template<class T> constexpr tag_t<T> tag={};

auto make_my_string(tag_t<some_type>){return "the string";}

then:

template<typename T>
class my_class{
private:
  static const std::string my_string;
};

template<class T>
static const std::string my_class<T>::my_string = make_my_string( tag<T> );

The per-type overhead is:

auto make_my_string(tag_t<some_type>){return "the string";}

which is cleaner than the alternative. As an advantage, you can define make_my_string in the namespace adjacent to some_type, and my_class should automatically pick it up via ADL.

As you have a pile of private static const members, you could also put them all into their own struct. Then you can have one function make all of them for a given type, instead of one function per private static const member.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524