liv2hak liv2hak - 3 months ago 13
C++ Question

class definition error: ‘SP’ is not a template type

I am tyring a custom implementation of smart pointers. The code is given below.

#include <iostream>
class Person
{
int age;
std::string pName;

public:
Person(): pName(0),age(0)
{
}
Person(std::string pName, int age): pName(pName), age(age)
{
}
~Person()
{
}

void Display()
{
std::cout << "Name: " << pName << "Age: " << age << std::endl;
}
void Shout()
{
std::cout << "Ooooooooooooooooooo" << std::endl;

}
};


/*Smart Pointer Interface */

class SP
{
private:
Person* pData; // pointer to person class
public:
SP(Person* pValue) : pData(pValue)
{

}
~SP()
{
/*pointer no longer requried*/
delete pData;
}

Person& operator* ()
{
return *pData;
}

Person* operator-> ()
{
return pData;
}
};


Trying to make it more generic.

template < typename T > class SP
{
private:
T* pData; // Generic pointer to be stored
public:
SP(T *pValue) : pData(pValue)
{
}
~SP()
{
delete pData;
}

T& operator*()
{
return *pData;
}

T * operator->()
{
return pData;
}
};

int main()
{
SP<PERSON> p(new Person("Scott", 25));
p->Display();
{
SP<PERSON> q = p;
q->Display();
/*Destructor of q will be called here..*/
}
p->Display();
/*Destructor of p will be called here.*/
return 0;
}


When I try to compile the above code I get the error.

smart_pointers.cpp:90:31: error: ‘SP’ is not a template type
template < typename T > class SP
^
smart_pointers.cpp: In function ‘int main()’:
smart_pointers.cpp:116:5: error: ‘SP’ is not a template
SP<PERSON> p(new Person("Scott", 25));


What is the reason for this?

Answer

You can't have two definitions of the same class.

struct S {};
template<typename T> struct S{};

reproduces your compiler error: http://ideone.com/7KpAPl

In this case, you only need the template definition.

Comments