c++functionclasstemplatesmixing

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;}

Solution

  • 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; }