I'm having a class which needs to have multiple overloads of the * operator. Some of these need to be declared as friends so I can have the class type as second argument. This is an example of a class which encounters the problem I'm about to present:
#pragma once
template<typename T>
class Example;
template<typename T>
Example<T> operator*(T value, Example<T> obj);
template<typename T>
class Example
{
private:
T m_data;
public:
Example(T);
friend Example operator*<T>(T, Example);
Example operator*(const T& other);
};
template<typename T>
Example<T> operator*(T value, Example<T> obj)
{
return value * obj.m_data;
}
template<typename T>
Example<T>::Example(T data) :m_data(data) { }
template<typename T>
Example<T> Example<T>::operator*(const T& other)
{
return Example(m_data * other.m_data);
}
This works but If I change:
template<typename T>
class Example
{
private:
T m_data;
public:
Example(T);
friend Example operator*<T>(T, Example);
Example operator*(const T& other);
};
with
template<typename T>
class Example
{
private:
T m_data;
public:
Example(T);
Example operator*(const T& other);
friend Example operator*<T>(T, Example);
};
I start getting a bunch of errors even though all I'm doing is swapping those 2 lines containing the declarations of the operator overloads. Can you explain me what is going on here? This makes no sense to me.
Code that generated error:
Example<int> a(2);
2 * a;
Errors:
unexpected token(s) preceding';' syntax error missing':' before '<' 'operator*': redefinition: previous definition was 'function' 'operator*': looks like a function but there is no parameter list. '*': uses 'Example<int>' which is being defined '*': friend not permitted on data declarations