Reputation:
I want a templated class that has two methods with the same name: One that takes a parameter of type T& and the other that takes Rational& as parameter where Rational is my class. I'm not sure whether this is called template specialization or just simple overloading One other thing is that I don't have an h and cpp file but an hpp file which contains the declaration with the implementation.
What would be the correct sytanx for this?
Somthing like this:
template <class T> class Matrix
{
bool hasTrace (Rational& trace) const
{
}
bool hasTrace (T& trace) const
{
}
}
Only this code doesn't compile and I get the compilation error:
..\/Matrix.hpp:200:7: error: 'bool Matrix<T>::hasTrace(T&) const [with T = Rational]' cannot be overloaded
..\/Matrix.hpp:180:7: error: with 'bool Matrix<T>::hasTrace(Rational&) const [with T = Rational]'
I now looked at this tutorial: enter link description here
Under Template specialization, it says that what I want to accomplish can be done by defining the specialized function outside of the class definition while replacing the template type with the specific type I wish to redefine the function for:
bool Matrix<Rational>::hasTrace (Rational& trace) const
{
}
but now I get this error:
..\/Matrix.hpp:227:6: error: specializing member 'Matrix<Rational>::hasTrace' requires 'template<>' syntax
Thanks again
Upvotes: 1
Views: 151
Reputation:
The solution is indeed to define the specialized method outside the class like this:
template <> bool Matrix<Rational>::hasTrace (Rational& trace) const
{
}
The reason that didn't compile at first was that I have implementation in this file which is an hpp file (I know it's really bad but this is an exercise and this is the only option we were given). Than, to add insult to injury I included this file in two cpp files at which point I got the error:
multiple definition of `Matrix<Rational>::hasTrace(Rational&) const'
@DanielFrey, thanks anyway for trying to help me!
Upvotes: 0
Reputation: 56921
You need to disable the second overload if T
is Rational
. With C++, you'd use a specialization:
template <class T> class Matrix
{
bool hasTrace (Rational& trace) const
{
}
bool hasTrace (T& trace) const
{
}
};
template<> class Matrix< Rational >
{
bool hasTrace (Rational& trace) const
{
}
};
With C++11, you could also use std::enable_if
:
#include <type_traits>
template <class T> class Matrix
{
bool hasTrace (Rational& trace) const
{
}
typename std::enable_if< !std::is_same< T, Rational >::value, bool >::type
hasTrace (T& trace) const
{
}
};
(or you could use Boost's type traits to achieve the same in C++98)
Upvotes: 1