Isuru
Isuru

Reputation: 1

Question regarding C++ Templates

I used a simple class for a test program about templates, this is what I did:

template <typename T>
class test
{
public:
    test<T>::test();
    T out();
};

template <typename T>
test<T>::test()
{
}

T test<T>::out()
{
}

int main()
{
    //test<int> t;
}

But when I try to compile it says 'T' : undeclared identifier and use of class template requires template argument list , pointing to the same line, where I have implemented the method out() . Can anyone please explain what the problem is?? I'm using visual studio 2008.

Upvotes: 0

Views: 149

Answers (4)

Meena
Meena

Reputation: 1

The issue in your code is related to the scoping of the template class and the definition of its member functions. When defining member functions outside the class template, you need to specify the template parameter (T) in the scope of the class. just remove the unnecessary test:: qualifiers from the member function declarations inside the class.The constructor and out() method definitions outside the class include the template parameter within the scope of the class template.

Upvotes: 0

Dewfy
Dewfy

Reputation: 23644

Following is more accurate:

template <typename T>
class test
{
public:
    test();
    T out();
};

template <typename T>
test<T>::test()
{
}

template <typename T>
T test<T>::out()
{
}

1) Don't use <T> inside class 2) Don't forget to declare template <T> before each method declaration out of class body

Upvotes: 5

Stewart
Stewart

Reputation: 4036

Your definition of the out member is missing the template argument list. out should read:-

template <typename T>
T test<T>::out() 
{ 
} 

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 186098

This line is wrong:

test<T>::test();

Just write this:

test();

Upvotes: 0

Related Questions