0

I have template member functions, but I cannot figure out how I can instantiate them when I am using them properly. The structure is as follows:

// foo.h
class Foo {
template<typename T>
T Func(T);
}
#include "foo.tpp"
// foo.tpp
template<typename T>
T Func(T input) {return(input);}

How should I instantiate the template if I want to realize the following code in the main function?

//main.cpp
#include "foo.h"
int main()
{
    Foo obj;
    int int_input, int_output;
    int_output = obj.Func(int_input);
    double double_input, double_output;
    double_output = obj.Func(double_input);
    return 0;
}

I have checked answers for similar questions such as Instantiation of template member function, but I do not want to instantiate all the member functions for all combinations every time I use them. Another option might be defining the class as a template class and instantiate different classes using template class Foo<int>;. However, this forces me to define different classes for different type of member functions, which I do not prefer. Is there other solution? Thank you very much!

fina12
  • 23
  • 1
  • 5

1 Answers1

0
template<typename T>
T Func(T input) {return(input);}

This declares a free-standing function template in the global scope that is unrelated to your Foo class. To implement the member function, you need to prefix the function definition's name with Foo::, as you would for any other member function implementation.

template<typename T>
T Foo::Func(T input){ return input; }

Also note that return(value); as opposed to return value; is a slight anti-pattern. While this doesn't usually matter, it can make a difference when using things like the decltype(auto) inferred return type and cause an accidental dangling reference.

alter_igel
  • 6,899
  • 3
  • 21
  • 40
  • Thank you very much for your extensive answer! I have never used `decltype(auto)`, so never had problem with `return()`yet. I will learn and check a little. – fina12 Mar 30 '20 at 17:09
  • It's a pretty advanced feature and you'll probably never need to worry about it. I just mentioned it for completeness' sake. – alter_igel Mar 30 '20 at 17:23