Pergunta

In VS2012 using c++11, why does this compile:

template <typename T>
class Vector2
{
public:
    Vector2();  //constructors

    T Dot(const Vector2<T>& U, const Vector2<T>& V);
};

template <typename T>
inline T Vector2<T>::Dot(const Vector2<T>& U, const Vector2<T>& V) //ISSUE
{ return (U.x * V.x + U.y * V.y); }

But this doesn't:

template <typename T>
class Vector2
{
public:
    Vector2();  //constructors

    template<typename G>
    G Dot(const Vector2<G>& U, const Vector2<G>& V);
};

template <typename G>
inline G Vector2<G>::Dot(const Vector2<G>& U, const Vector2<G>& V) //ISSUE
{ return (U.x * V.x + U.y * V.y); }

The second causes an error: "unable to match function definition to an existing declaration"
I realize I don't have to use G for the later template function definition, I've just used it to be consistent with the 2nd example declaration.
Are you not allowed to have a function in a template class that takes a different type than the class? I'm extremely interested in finding out what's going on here and anything relevant about templates I can learn from this error.

Foi útil?

Solução

You have two template types: T and G. One list (T) is for the class, and one (G) is for the member function. Therefore, you have to have two lists; one for the class, then one for the function (and make sure that the right types go in the right places, T after the class name and G in the parameters):

template<typename T>
template<typename G>
inline G Vector2<T>::Dot(const Vector2<G>& U, const Vector2<G>& V)
{ return (U.x * V.x + U.y * V.y); }

Outras dicas

You need two separate template declarations:

template <class T>
template <class G>
inline G Vector2<T>::Dot(const Vector2<G>& U, const Vector2<G>& V) {...}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top