Christian Galleisky
Christian Galleisky

Reputation: 21

Mixing Class and Function templates

Hi I am trying to make a C++ class template and have it poses a function template too.. it boils down to

template <class T> 
class fun{
public:
    template<class U, class V> T add(U, V);
private:
    T data;};

I've have tried rewriting the signature in the cpp file (as opposed to the header file written above) many different ways. I'm starting to think that you can't have a class as a template AND have it have function templates as well.. Can you?

In the cpp file it looks like this and I get an error saying my declaration of the function "add" in the cpp file is incompatible with my declaration of "add" in the header file.

This is my function template in the cpp file.

template <class T, class U> T fun<T>::add(T a, U b){return a+b;}

Upvotes: 1

Views: 919

Answers (2)

jackw11111
jackw11111

Reputation: 1547

The class template definitions need to be known at compile-time to generate the class from the template, so the most common method is to include the definitions in the header file. If you still want to keep the interface and method definitions seperated you could use a .tpp file.

Here's a general approach, that creates a class from externally unique data types.

I.e. That you want template <class U, class V> T fun<T>::add(U a, V b){return a+b;} instead of template <class T, class U> T fun<T>::add(T a, U b){return a+b;}

header.h:

template <class T>
class fun{
public:
    template<class U, class V> T add(U, V);
private:
    T data;
};

#include "header.tpp"

header.tpp:

// out of class definition of fun<T>::add<U, V> 
template<class T> // for the enclosing class template
template<class U, class V> // for the member function template
T fun<T>::add(U a, V b) { return a + b; }

Upvotes: 1

MTMD
MTMD

Reputation: 1232

Yes you can have a class template that includes a function template. Your problem is that you are trying to remove function definitions from header files. When you are using templates, you should include the function definitions in the header file. Note that you can practice such pattern only when you use template. Here is an example:

header.h

template <class T>
class fun{
public:
  template<class U, class V> T add(U u, V v) {
          return u + v;
  }
private:
  T data;
};

main.cpp

#include <iostream>
#include "header.h"

int main () {
        fun<int> f;
        std::cout << f.add(10, 12) << std::endl;
}

Upvotes: 0

Related Questions