1

My (broken) code:

// hpp file
#include <iostream>
#include <string>

class iHello {
  public: virtual void hello(void) = 0;
};

template<typename T> class foo : public iHello {
  public: void hello(void) { std::cout << "Say hello :" << key << std::endl; }
  private:
    static const std::string key;
};

template<typename T> const std::string foo<T>::key = "all foo<T>";

// cpp file
class boo: public foo<boo> { };

class bar: public foo<bar> { };
template<typename T> const std::string foo<bar>::key = "bar"; // error

class baz: public foo<baz> { };
template<typename T> const std::string foo<baz>::key = "baz"; // error

int main(int argc, char ** argv) {
    boo a;
    bar b;
    baz c;

    a.hello();
    b.hello();
    c.hello();

    return 0;
}

My desired output would be:

Say hello :all foo<T>
Say hello :bar
Say hello :baz

But I can't figure out how to initialize the static constant member key based on the templated class.

If I can't do both (general and specific cases), then my preference is that I would have to explicitly define key for each templated class created.

Is there a way to do this?

Jamie
  • 7,075
  • 12
  • 56
  • 86

1 Answers1

2

The correct syntax for full specialization of static members in definition should be:

template<> const std::string foo<bar>::key = "bar";
template<> const std::string foo<baz>::key = "baz";
songyuanyao
  • 169,198
  • 16
  • 310
  • 405