1

I have a problem when use the templates with a method parameter inside a class.
The following is an example but not my real code which has the problem, in order to simplify the code.

Class declaration:

class Test {

public:
    Test();
    template <class T>
    void PrintData(T info);
};

Class definition:

Test::Test(){}

void Test::PrintData(T info){
    cout << info << endl;
}

When usage:

int main(){
    Test test;
    test.PrintData<const char*>("Thank you.");

    return 0;
}

The error messages:

  • variable or field 'PrintData' declared void
  • 'T' was not declared in this scope

What is the problem in my code, and/or how to use the templates with the method parameter correctly ?

Lion King
  • 32,851
  • 25
  • 81
  • 143

3 Answers3

2
template<typename T>
void Test::PrintData(T info){

would be the correct definition of that function. Along with that include definitions also in header.

ravi
  • 10,994
  • 1
  • 18
  • 36
0

in class definition section where u defied your PrintData function, reference of template is required

so your definition will be like this template <class T> void Test::PrintData(T info){ cout << info << endl; }

Abdullah
  • 2,015
  • 2
  • 20
  • 29
0

You need to put the definition of the template member function in the header file and it should work fine.

header:

#include <iostream>

class Test 
{
public:
    Test();
    template <class T>
    void PrintData(T info);
};

template <class T>
void Test::PrintData(T info)
{
    std::cout << info << std::endl;
}
rozina
  • 4,120
  • 27
  • 49