jrd1
jrd1

Reputation: 10726

Accessing class template members from static functions of a specialized template of the same class

I am still learning C++ templates, and have encountered a problem regarding calling members from specialized static functions using the following. GCC complains: "invalid use of member C< const char* >::value in static member function." I have searched this forum and a few others, and even my friend Google cannot aid me. I figure the error has to be something I am overlooking, as I made a non-specialized version of the class (with the same static member function), and I still get the same error. Any ideas?

template <typename T = const char*>
class C { };

//specialization for const char*
template <>
class C <const char*> {
  public:
    C() { }

    static void echo(int x);

  private:
    int value;
};

//error occurs here
void C<const char*>::echo(int x) {
  value = x;
}

Many thanks to any insight you can offer.

Upvotes: 0

Views: 150

Answers (2)

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52157

The echo() is static an therefore cannot access the instance-level field value.

Either make the function non-static or make the field static.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283961

It has nothing to do with templates.

value is an instance member, and can only be accessed when you provide an instance of C. A static function has no this instance, and you haven't used the . or -> member access operator either to explicitly provide an instance.

Upvotes: 2

Related Questions