1

I have a structure in which the operator template type. Want to make the correct announcement of this structure in header. Write the following code

header file

struct add_positive {
    template<typename T>
    T operator()(T value, const T& now);
};

.cpp file

template<typename T>
add_positive add_positive::operator()(T value, const T& now) {
    if (now >= 0) {
        return value + now;
    }

    return value;
}

But when compiling get the following error:

error: prototype for ‘add_positive add_positive::operator()(T, const T&)’ does not match any in class ‘add_positive’ add_positive add_positive::operator()(T value, const T& now) { error: candidate is: template<class T> T add_positive::operator()(T, const T&) T operator()(T value, const T& now);

Can't understand what I did wrong?

Victor
  • 333
  • 2
  • 10
  • Unrelated for now, but please read https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – user0042 Jul 09 '17 at 16:17
  • you can't separate the definition and declaration of templated functions into different files. The compiler needs to know the type and definition at compile time to make the appropriate substitutions. – jodag Jul 09 '17 at 16:19

1 Answers1

1

You can simply use an inline definition:

struct add_positive {
    template<typename T>
    T operator()(T value, const T& now) {        
        if (now >= 0) {
           return value + now;
        }
        return value; 
     }   
};

Note that you usually have to provide a definition for your templated function in the header file.

In the header the following should equally work:

struct add_positive {
    template<typename T>
    T operator()(T value, const T& now);
};

template<typename T>
T add_positive::operator()(T value, const T& now) {        
    if (now >= 0) {
       return value + now;
    }
    return value; 
 }   
user0042
  • 7,917
  • 3
  • 24
  • 39