Apratim Das Apratim Das - 16 days ago 4
C++ Question

Member function not declared when using templates in classes (C++)

I am using the following classes in my code

class pos2d
{
float x, y;
public:
float getx() const;
float gety() const;
//int getz() const; //How to avoid??
};

class pos3d
{
float x, y, z;
public:
float getx() const;
float gety() const;
float getz() const;
};

template<class T, class P>
class entity
{
T type;
P position;
public:
void print() const;
};


My print function in class entity is as follows

template<class T, class P>
void entity<T, P>::print() const
{
if (type == 1 || type == 'A')
cout << "Object is of type " << type << " and has coordinates as (" << position.getx() << ", " << position.gety() << ", " << position.getz() << ")\n\n"; //Avoid getz in pos2d
else if (type == 2 || type == 'B')
cout << "Object is of type " << type << " and has coordinates as (" << position.getx() << ", " << position.gety() << ")\n\n";
}



Note, Type value changes depending of whether class is pos2d or pos2d.


During compilation I get the following error:


Error C2039 'getz': is not a member of 'pos2d' Project1


I am aware that using a common get() function would solve this but i wish to be able to use getz() in my code without having it as part of another common function.

Answer

The problem is if you pass pos2d as template parameter the line

cout << "Object is of type " << type << " and has coordinates as (" << position.getx() << ", " << position.gety() << ", " << position.getz() << ")\n\n";

is still instantiated (if is done at runtime), the function cannot be resolved.

The usual way is to use specializations (Type parameter can be omitted):

template<class P>
class entity
{
    P position;
public:
    void print() const;
};

template<>
void entity<pos3d>::print() const
{
    cout << "Object is of type pos3d and has coordinates as (" 
         << position.getx() << ", " << position.gety() << ", " << position.getz() << ")\n\n";
}        

template<>
void entity<pos2d>::print() const
{
        cout << "Object is of type pos2d and has coordinates as (" 
             << position.getx() << ", " << position.gety() << ")\n\n";
}