3

Recently I stumbled upon such piece of code:

template <typename Ta> template <typename Tb>
void SomeClass<Ta>::Function() {}

There is template function, but it has strange syntax, which I don't really understand. What does it do? Is it anwhere near template<template<typename Ta>>?

I have never met such syntax, and I am confused.

Adam Kaczmarski
  • 338
  • 1
  • 12
  • 5
    Heads up: a “template function” doesn’t exist in C++. C++ has *function templates*. There’s a crucial difference: a function template *is not a function*. It’s a *template* to *make* a function (by instantiating it with template arguments). – Konrad Rudolph Sep 15 '20 at 07:51
  • Related: [Defining a Single Template for a Member Function within a Class Template with Both Templates Used in Member Function](https://stackoverflow.com/questions/63896028/) – Remy Lebeau Sep 15 '20 at 07:53

2 Answers2

11

Sometimes all it needs is a complete example:

template <typename Ta>
struct SomeClass {
    template <typename Tb>
    void Function();
};


template <typename Ta> template <typename Tb>
void SomeClass<Ta>::Function() {}

int main() {
    SomeClass<int> sc;
    sc.Function<double>();
}

It is a definition of a method template of a class template.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
2

Sometimes You need compatibility with compatible objects while writing templates. For example int and double are compatible with each other. But if you have a template class objects lets say Something<int> and Something<double> and you try to assign them it will not work. You do this especially while writing copy or move assignment operators or constructors. Let suppose we have an a class template Something.

template <typename T>
class Something {
public:
    Something();

    Something(const Something& obj) : data(obj.data)
    {
    
    };

 
private:
    T data;
};

int main(){
    Something<int> number;
    Something<double> double_number;

    Something<double> newObj(number);
}

if you try to do this, it will not compile.

To make it compile you make template of your copy constructor as in this case. To make it compile you have to something like this.

template <typename T>
class Something {
public:
    Something();

    template<typename E>
    Something(const Something<E>& obj);

    T get_data() const{
        return data;
    } 
private:
    T data;
};

template<typename T>
template <typename E>
Something<T>::Something(const Something<E>& src): data(src.get_data()){

}

int main(){
    Something<int> number;
    Something<double> double_number;

    Something<double> newObj(number);
}

Note that we are calling the public method to assign data to this object because Something<int> and Something<double> both are of different types.

foragerDev
  • 1,307
  • 1
  • 9
  • 22