jeudi 15 novembre 2018

How can I initialize a static const string of a template for each class type the templated class creates?

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;
};

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

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.

Is there a way to do this?

Aucun commentaire:

Enregistrer un commentaire