0

Noobie programmer here, just learning class templates for c++.

My current project requires me to make a template class that can take ints, doubles, or strings as parameters.

So far, every time I have created the implementation of the class functions, i have to make 3 of each function (one for each parameter type).

My question is, if the implementation of a particular class function is exactly the same regardless of the parameter type, is there a way to just write one implementation for it?

Thanks in advance to all replies!

Zach Ross-Clyne
  • 779
  • 3
  • 10
  • 35

1 Answers1

0

This question is slightly unclear - first you say that the class template takes different parameters, but then it sounds like your member functions are taking these different parameters instead.

If your template class looks like

template<typename T>
class X
{
public:
    X(const T& t) : m_t(t) {}
    void print();
private:
    T m_t;
};

Your implementation of print could look like this:

template<typename T>
void X<T>::print() 
{ 
    std::cout << m_t; 
}

A member function can also be a template:

template<typename T>
class X
{
public:
    X(const T& t) : m_t(t) {}

    template<typename U>
    void printBefore(const U& u);
private:
    T m_t;
};

The definition of a function template within a class template looks like this:

template<typename T>
template<typename U>
void X<T>::printBefore(const U& u) 
{ 
    std::cout << m_t << u; 
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • sorry if my question was unclear. My problem has mostly been linker errors when I attempt to separate the implementation from the interface of the template class. I even tried it the way you wrote it on your reply but still linker error. – user5540318 Nov 23 '15 at 12:41
  • @user5540318 See http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file. – Quentin Nov 23 '15 at 12:44
  • @user5540318 Why didn't you ask about your actual problem? I'm going to close this question as a duplicate. – molbdnilo Nov 23 '15 at 12:49