c++ - Initializing a static const for a template specialization -


i have created class template static const element. intent each specialization of template have own version / value of static element. here sample code:

template < typename t > class c {    public:       static const std::string name;       t something;       void printname() { std::cout << name << std::endl; } };  class c1 : public c< int >{}; class c2 : public c< char >{};  template<> const std::string c< int >::name{ "my int" };   // compiles template<> const std::string c< char >::name{ "my char" }; // compiles  //template<> const std::string c1::name{ "my int" };   // doesn't compile //template<> const std::string c2::name{ "my char" };  // doesn't compile  //const std::string c1::name{ "my int" };   // doesn't compile //const std::string c2::name{ "my char" };  // doesn't compile  int main() {    c1 c1;    c2 c2;     c1.printname();    c2.printname();     std::cout << c1.name << "  " << c2.name << std::endl;    std::cout << c1::name << "  " << c2::name << std::endl; } 

when using compilable version, output expect:

my int char int  char int  char 

for lines don't compile, error message (using gcc 4.4) says

iso c++ not permit 'c<int>::name' defined 'c1::name' 

why not permitted? understanding full specialization of template class in (?) respects, , class has members declared in template. expect able refer static members of class using scope resolution operator. apparently can after initialization, in last line of main above, not in initialization itself.

can provide insight why standard written way? kind of problems arise if standard allowed 'bad' syntax above?

it looks me problem you're encountering has nothing templates. problem you're trying define static member using derived class in nested-name-specifier, not original class. have same issue here:

struct {     static int x; }; struct b : a{}; int b::x = 42; 

the c1 , c2 in code not full specializations of c, rather, derived classes of specializations of c. don't know you're expecting here...


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -