Caio
Caio

Reputation: 55

How do I access a template class member field in a specialised template class in C++?

I am trying to write a template class that has a member of the passed type which is supposed to be used on a method of an specialised template class. Like this:

template <class T>
class MyTemplateClass
{
public:
    MyTemplateClass() {}

    void DoSomething()
    {
        DoSomethingWithMember();
    }

    void DoSomethingWithMember() {}

protected:
    T m_member;

};

template<>
class MyTemplateClass<float>
{
public:
    void DoSomethingWithMember()
    {
        printf("Member is %f", m_member);
    }
};

So that I can make calls like:

MyTemplateClass<float> obj2 = MyTemplateClass<float>();
obj2.DoSomething();

The specialised template class won't compile, gives the error:

"Use of undeclared identifier m_member".

Is there a way for the specialised template class to access the original class members without having the code duplicated with the new specialised type? Or any other way to achieve what I'm trying to do here?

Upvotes: 1

Views: 387

Answers (2)

Jarod42
Jarod42

Reputation: 217850

Alternatively, you may specialize only one method, something like:

template <class T>
class MyTemplateClass
{
public:
    MyTemplateClass(T t) : m_member(t) {}

    void DoSomething() { DoSomethingWithMember(); }

    void DoSomethingWithMember();

protected:
    T m_member;

};

// **Fully** Specialize DoSomethingWithMember for float.
template <>
void MyTemplateClass<float>::DoSomethingWithMember()
{
    std::cout << "Member is " << m_member;
}

Demo

Upvotes: 1

R Sahu
R Sahu

Reputation: 206697

So that I can make calls like:

MyTemplateClass<float> obj2 = MyTemplateClass<float>();
obj2.DoSomething();

The specialised template class won't compile, gives the error: "Use of undeclared identifier 'm_member'".

That's because the template specialization has no relation to the generic class template. Anything that the specialization needs must be implemented in the specialization. Such as:

template<>
class MyTemplateClass<float>
{
   public:
      void DoSomething()
      {
         DoSomethingWithMember();
      }

      void DoSomethingWithMember()
      {
         printf("Member is %f", m_member);
      }

      float m_member;
};

Upvotes: 1

Related Questions