Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward Declaration of Template Function

I have a template class with a friend template function. I currently have the following code and it is working:

template<class T>
class Vector
{
  public:
    template<class U, class W>
    friend Vector<U> operator*(const W lhs, const Vector<U>& rhs);
}

template<class U, class W>
Vector<U> operator*(const W lhs, const Vector<U>& rhs)
{
  // Multiplication
}

I would prefer for my solution to have forward declaration of the friend function so that I can have the security benefits and one-to-one correspondence that it provides compared to my current method. I tried the following but keep running into errors.

template<class T>
class Vector;

template<class T, class W>
Vector<T> operator*(const W lhs, const Vector<T>& rhs);

template<class T>
class Vector
{
  public:
    friend Vector<T> (::operator*<>)(const W lhs, const Vector<T>& rhs);
}

template<class T, class W>
Vector<T> operator*(const W lhs, const Vector<T>& rhs)
{
  // Multiplication
}
like image 260
noddy Avatar asked Feb 28 '13 00:02

noddy


People also ask

What is forward declaration of a function?

In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.

How do you declare a template function?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.

Where do you put forward declaration?

Generally you would include forward declarations in a header file and then include that header file in the same way that iostream is included.

Why forward declaration is used?

A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.


1 Answers

I think you almost had it. You just needed to make the function a single parameter template when you friend it. The following compiles on g++ 4.5 although since I can't test the instantiation with your test case I'm not 100% sure it will solve your real problem.

template<class T>
class Vector;

template<class T, class W>
Vector<T> operator*(const W lhs, const Vector<T>& rhs);

template<class T>
class Vector
{
  public:
    template<class W>
    friend Vector<T> operator*(const W lhs, const Vector<T>& rhs);
};

template<class T, class W>
Vector<T> operator*(const W lhs, const Vector<T>& rhs)
{
  // Multiplication
}
like image 72
Mark B Avatar answered Oct 14 '22 07:10

Mark B