Declaration of Templates


How are templates declared in the header file?
E.g. I have the following function template in .cpp:


template<typename T>
bool Class::Check(const T &value)
{
return value != value;
}


What is the difference from the above template to the one
below? The difference is the "bool and the T", could you
please explain this?


template <typename T>
T max(T x, T y)
{
return (x > y) ? x : y;
}

Thanks for help.
The difference is the "bool and the T", could you
please explain this?


Well the first function belongs to a larger template class, called Class (A poor name for a class by the way.). The second is a template function that is not part of an actual class.

The first snippet, the member function, compares the value passed into the function with a value held in the class and returns whether the two values are equal or not, a bool value.

The second, non-class function, compares the two values passed into the function and returns the higher value. Note that both of the parameters and the return value have the same type 'T'.

And how are the templates declared in the header?
The templates aren't normally defined in the .cpp file, but in the header file.

So the example code you've provided should go in the header file.
Note that this compares the argument value with itself.
1
2
3
4
5
template<typename T>
bool Class::Check(const T &value)
{	
      return value != value;  // **** 
}


Perhaps, this is what was intended:
1
2
3
4
5
template<typename T>
bool Class::Check( const T &value ) const // EDIT: make it const-correct
{	
      return value != Class::value;  // **** 
}
Last edited on
Topic archived. No new replies allowed.