I have a matrix class that supports operations with scalar values that I implemented using operator overloading. Since each overloaded operator function has the same body except for the operator being used, I decided to create a generic function that would accept a function along with the matrix and a scalar value to consolidate my code.
Here is the generic function and it being called from the overloaded addition operator function:
// Generic function to take care of matrix operations
template<typename T, typename F>
Matrix<T> scalar_operation(const Matrix<T> &a, const T b, F f) {
std::vector<std::vector<T> > new_els = a.elements;
typename std::vector<std::vector<T> >::iterator it = new_els.begin();
typename std::vector<T>::iterator it_in;
for (; it != new_els.end(); ++it) {
it_in = it->begin();
for (; it_in != it->end(); ++it_in) {
*it_in = f(*it_in, b);
}
}
return Matrix<T>(new_els);
}
// Add scalar to all values in Matrix
template<typename T>
Matrix<T> operator+(const Matrix<T> &a, const T b) {
return scalar_operation(a, b, std::plus<T>());
}
And here are the functions declared in the matrix class:
template<class T>
class Matrix {
template<typename F>
friend Matrix<T> scalar_operation(const Matrix<T> &a, const T b, F f);
friend Matrix<T> operator+<>(const Matrix<T> &a, const T b);
friend Matrix<T> operator-<>(const Matrix<T> &a, const T b);
friend Matrix<T> operator*<>(const Matrix<T> &a, const T b);
friend Matrix<T> operator/<>(const Matrix<T> &a, const T b);
When I implemented the overloaded operator functions separately, they worked, but with this implementation, I get the following compiler error:
Undefined symbols for architecture x86_64:
"Matrix<float> scalar_operation<std::__1::plus<float> >(Matrix<float> const&, float, std::__1::plus<float>)", referenced from:
Matrix<float> operator+<float>(Matrix<float> const&, float) in matrix_test-3188cd.o
ld: symbol(s) not found for architecture x86_64
I imagine my error is related to the Matrix<float> scalar_operation<std::__1::plus<float> >( line because it looks like the linker is searching for a function with this header, which is slightly different from how it's declared in my file, but I've tried modifying my declaration and it throws additional errors.
Why am I getting this error and how can I fix it? Thanks!
EDIT: To clear up some confusion, all the code has been implemented in the header file since it is a templated class. There is no corresponding .cpp file.
The code has the following problem: class Matrix declares the friend function friend template<typename F> scalar_operation(...) (yes, friend keyword not only states the private access, it also declares a function), but there is no such function in outer scope. There is only the template<typename T, typename F> scalar_operation, that does not satisfy friend Matrix's declaration. Why? Let's try to pseudocode instantiations that can be made with float and std::plus<float> (return values and arguments omitted for shortness):
friend scalar_operation<std::plus<float>>(...)
and
scalar_operation<float, std::plus<float>>(...).
As we can see they are different. So during compilation we have no problem: we have proper friend scalar_operation declaration that satisfies calling convention inside operator+. But no definitions of such declaration can be made, and we get a problem while linking. The solution is a proper friend declaration:
template<typename TT, typename F>
friend Matrix<TT> scalar_operation(const Matrix<TT> &, const TT, F);
Related
I have a template struct "point as follows:
template<typename T>
struct point
{
T x, y, z;
template<typename T1>
inline point<T> operator*(const point<T1>& p) const // multiply by another point.
{
return point<T>{this->x*p.x, this->y*p.y, this->z*p.z};
}
template<typename T1>
inline point<T> operator*(const T1& v) const // multiply by constant from right side
{
return point<T>{this->x*v, this->y*v, this->z*v};
}
}
template<typename T1, typename T2>
inline point<T1> operator*(const T2& v, const point<T1>& p) // multiply by a constant from the left side.
{
return point<T1>{p.x*v, p.y*v, p.z*v};
}
The two operator overloading functions that declared as member functions, the first one is supposed to multiply by another point, and the other to multiply a point by a constant from the right side, where the one declared outside the struct is to do the same thing but from the left side.
And now when I go to compile the following code:
point<double> p1{1,2,3};
point<float> p2{1,2,3};
point<double> p3 = p1*p3;
The compiler calls the one declared outside the struct instead of the one declared as a member function, and produces and error:
error: cannot convert ‘point<double>’ to ‘float’ in initialization
return point<T1>{p.x*v, p.y*v, p.z*v};
And that makes sense, because the both arguments are template variables and can be interpreted as point variables. Now the second one can be only a point variable, but the first one can be anything!
To solve this I can go and write several copies of that function, when declaring the first argument once as int, float, double, long double .. et cetera. This works fine for me, but I'm still wondering if there is a better way to deal with this, and if I can write only one copy as above?
Do not unnecessarily overload operators as member functions,
follow the rules described here.
Having operator* for two point instances return the type of the left one does not make sense, in my opinion. Better consider both types in the deduction of the return type, since the function is defined as commutative.
template<typename T>
struct point
{
T x, y;
};
template<typename T1, typename T2>
auto operator*(const point<T1>& lhs, const point<T2>& rhs)
-> point<decltype(std::declval<T1>() * std::declval<T2>())>
{
return {lhs.x*rhs.x, lhs.y*rhs.y};
}
template<typename T1, typename T2>
point<T1> operator*(const point<T1>& p, const T2& v)
{
return {p.x*v, p.y*v};
}
template<typename T1, typename T2>
point<T1> operator*(const T2& v, const point<T1>& p)
{
return p * v;
}
Try to do the same with the overloads for multiplication by a scalar as an exercise.
I have written a matrix class. I have overloaded the operator+, so that the user can write: matrix + 2. I would like the user to also write: 2 + matrix.
For the standard format (i.e. the object invoking 2) I have written a standard operator overloading function. It works.
template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
Matrix result(rows, cols, 0.0);
for (unsigned i = 0; i < rows; ++i)
{
for (unsigned j = 0; j < cols; ++j)
{
result(i,j) = (*this)(i, j) + rhs;
}
}
return result;
}
Now for the other order (i.e. 2 + matrix), I have written the friend function:
// Friend Functions that allow the user to write expressions in a different order
template<typename T>
friend Matrix<T> operator+(const T& type, const Matrix<T>& matrix);
and implementation as:
template<typename T>
Matrix<T> operator+(const T& type, const Matrix<T>& matrix)
{
return matrix + type;
}
When I try to write 2 + matrix (in main()), I get some errors.
I have always had problems using friend functions with generic classes and frankly, I have never understood why it never works for me.
Could someone please explain what I am doing wrong here?
Errors I get:
IntelliSense: no operator "+" matches these operands operand types are: int + Matrix
Severity Code Description Project File Line Error C2244 'Matrix::operator +': unable to match function definition to an existing declaration
It looks like it's just a template deduction error; that is to say that your compiler can't deduce the proper function based on the templated friend function.
Since your friend function is a simple function, you could just declare it in your class/header and the compiler should be able to deduce it properly (as well as possibly inline it if optimizations are turned on); just declare the friend function in your header like such:
friend Matrix operator+(const T& type, const Matrix& matrix)
{
return matrix + type;
}
You don't need to specify the template keyword since it's within your template specialized class.
Hope that can help.
You can fix the problem simply by changing the member function to const.
template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
...
}
I created a matrix class with templates:
template <typename T>
class Matrix
{
static_assert(std::is_arithmetic<T>::value,"");
public:
Matrix(size_t n_rows, size_t n_cols);
Matrix(size_t n_rows, size_t n_cols, const T& value);
// Functions
// Operators
Matrix<T>& operator*=(const T& value)
private:
size_t rows;
size_t cols;
std::vector<T> data;
};
I created the following two (external) operators to multiply my matrix with a number:
// Inner operator used by the externals ones
template <typename T>
inline Matrix<T>& Matrix<T>::operator*=(const T& value)
{
for(size_t i(0); i < data.size(); i++)
{
data[i] *= value;
}
return *this;
}
template <typename T>
inline Matrix<T> operator*(const T& value, const Matrix<T>& matrix)
{
Matrix<T> tmp(matrix);
return tmp *= value;
}
template <typename T>
inline Matrix<T> operator*(const Matrix<T>& matrix, const T& value)
{
return value * matrix;
}
The problem is that if I declared the matrix as a double, I can multiply the matrix only by doubles and so on...
Matrix<double> m1(3,3,1.);
5. * m1; // Works
5 * m1; // Doesn't work (5 is an int and not a double)
How can I fix this behave? It is possible to let doubles be multiplied by others arithmetic types?
Sure, just allow two parameters to your templated free functions and member functions.
For example:
template <typename T> class Matrix {
/* ... */
template <typename U>
inline Matrix<T>& operator*=(const U& value)
{
for(size_t i(0); i < data.size(); i++)
{
data[i] *= value;
}
return *this;
}
};
template <typename T, typename U>
inline Matrix<T> operator*(const U& value, const Matrix<T>& matrix)
{
Matrix<T> tmp(matrix);
return tmp *= value;
}
This will trigger compiletime errors if you try to multiply your Matrix with something nonsensical, that is, if T*U is undefined.
Yes. Declare the function in the Matrix class as
template <typename T>
class Matrix
{
public:
/* ... */
template <typename S>
inline Matrix & operator*=( const S & value );
/* ... */
};
The definition looks like
template <typename T>
template <typename S>
inline Matrix<T>& Matrix<T>::operator*=(const S& value)
{
for(size_t i(0); i < data.size(); i++)
{
data[i] *= value;
}
return *this;
}
for the member function. You need to write template twice. A bit odd, but that's C++ syntax.
In case of the free functions you can write
template <typename T, typename S>
inline Matrix<T> operator*(const S& value, const Matrix<T> &mat)
{
Matrix<T> tmp(mat);
return tmp *= value;
}
The problem that you are seeing is that template type deduction requires a perfect match of all of the deduced types. In your case you have a template that takes a single type argument T that is both the scalar and the matrix types. When the compilers sees the operation: 5 * m1, it deduces T == int for the first argument but T == double for the second argument, and type deduction fails.
There are multiple approaches around this, as it has been suggested, you can add a second template argument:
template <typename T, typename S>
Matrix<T> operator*( Matrix<T> m, S scalar ) {
return m*=scalar;
}
[Note: both arguments by value, the second one because for arithmetic types it is more efficient and idiomatic to pass by value; the first one because by moving the copy to the interface of the function you allow the compiler to elide copies]. This approach is simple, but will generate one operator* for each combination of S and T in the program, even though the actual multiplication in operator*= is always performed on T.
Another approach would be to fix the type of the scalar that you want to multiply by, for example, make it double, generating only one operator* per T type that is multiplied:
template <typename T>
Matrix<T> operator*( Matrix<T> m, double scalar ) {
return m*=scalar;
}
In this approach there is a single operator*, the one taking a double as argument. As in the previous example, it might require two type conversions on the scalar (say you multiply Matrix<int> by 5, it will then convert 5 into a double, which will then be converted back to int to match the signature of operator*=.
The third approach is to create a non-templated function that takes your Matrix and another argument of the same type. This will be the closest to your original code, with the slight advantage that not being a template, it will allow conversions for the scalar argument. Theoretically you could define all such functions yourself manually:
Matrix<int> operator*( Matrix<int>, int ) { ... }
Matrix<double> operator*( Matrix<double>, double ) { ... }
But this becomes a maintenance problem very easily. Luckily, there is a feature in the language that allows for the definition of all those non-template functions generically. Although the syntax might not be the most natural. You just need to declare the free function as a friend of your template, and define it inside the class template definition:
template <typename T>
class Matrix {
// ...
friend Matrix operator*( Matrix m, T scalar ) { return m*=scalar; }
};
As we are inside the class template Matrix, we can use Matrix (without arguments) to refer to the current instantiation (Matrix<int>, Matrix<double...) [This might not seem obviously important, but it is, it is important to realize when Matrix refers to the template, and when it refers to the class generated from the template]. The second argument to the function is T. Again, this is not the generic T of the class template, but the current instantiating type (int, double...).
The language allows for the definition of a friend function inside the class that has the declaration, and that will define the function at namespace level, although the declaration will only be found through Argument Dependent Lookup.
Whenever you instantiate a particular instance of your template (say Matrix<int>) and call the operator, the compiler will generate the free function for you. Because the function is not templated, it will allow conversions on the arguments, and thus for Matrix<int> m it will allow you to call m * 5. by converting 5. into an int.
I'm trying to overload the + operator in a forest class, a forest being a collection of trees, and the + operator is supposed to combine two forests into one. I have the following code as my class definition:
template<typename NODETYPE>
class Forest
{
public:
friend Forest& operator+<>(Forest&, Forest&);
friend ostream& operator<<<>(ostream&, const Forest&);
friend istream& operator>><>(istream&, Forest&);
Forest();
Forest( const Forest& otherForest);
~Forest();
void nodes(int&) const;
private:
ForestNode<NODETYPE> *root;
ForestNode<NODETYPE> *getNewNode( const NODETYPE &);
};
The following is my implementation of operator+:
template<typename NODETYPE>
Forest& operator+<>(Forest& f1, Forest& f2)
{
f3 = new Forest();
f3.root = *f1.*root;
f3.root.sibling = *f2.*root;
*f1.root = 0;
*f2.root = 0;
return f3;
}
I get the following error on compile:
|28|error: expected constructor, destructor, or type conversion before '&' token|
line 28 refers to the signature of my operator+ implementation.
I think to correct it i am supposed to add to the return type, giving:
template<typename NODETYPE>
Forest<NODETYPE>& operator+<>(Forest& f1, Forest& f2)
{
f3 = new Forest();
f3.root = *f1.*root;
f3.root.sibling = *f2.*root;
*f1.root = 0;
*f2.root = 0;
return f3;
}
But that gives me the following errors:
|28|error: declaration of 'operator+' as non-function|
|28|error: missing template arguments before '&' token|
|28|error: 'f1' was not declared in this scope|
|28|error: missing template arguments before '&' token|
|28|error: 'f2' was not declared in this scope|
Can anyone help me with this? I'd be very very thankful.
The key to writing operator+ is don't write operator+. Instead, write a copy ctor and operator+=:
template<class NodeType>
struct Forest {
//...
Forest(Forest const &other);
//...
Forest& operator+=(Forest const &other) {
// code here
return *this;
}
//...
};
Now we add operator+:
template<class NodeType>
struct Forest {
//...
friend Forest operator+(Forest a, Forest const &b) {
a += b;
return a;
}
//...
};
And that's it! Copying is usually straight-forward (sometimes by being disallowed) and it may be simpler to think in terms of += than + (you have two objects and mutate one, rather than create a third object out of two). This pattern for op+ works with any similar type, and even for similar operators such as -, *, and /.
Operator overloading can be a good or a bad thing. Good when it leads to simpler looking code. Bad when it leads to writers either overloading with incorrect semantics (yet a solution that compiles) or where the intuitive way to use the operator leads to highly inefficient code.
Note the latter statement can apply to std::string too, which could potentially make large numbers of copies, and which is why the C++03 standard states that a string does not have to be stored internally in a contiguous buffer (in the old days they used copy-on-write references to and could store such references to both strings being concatenated until required. Subsequently it was found to be non-threadsafe and making it so was more costly than simply copying the buffer so now they copy every time and are inefficient again).
(Note that the C++11 standard which recognises threading and atomic issues ensures that the underlying does need to be contiguous and null-terminated to make read operations safe).
The correct signature of operator+ (in the case all are the same type) is as follows:
T operator+( const T&, const T& );
As a member function it would be:
class T
{
// make public if necessary
T operator+( const T& rhs ) const;
};
You can implement operator+ automatically as a template whenever operator += is available with
template<typename T, typename R>
T operator+( const T& lhs, const R& rhs )
{
T copy(lhs);
return copy += rhs;
}
If you want to declare an overloaded operator of your template as a friend, this is the correct way to do it. I will show it with operator<<
// first some forward declarations, assume ostream already declared with #include <iosfwd> minimum
template< typename T > class Forest;
template< typename T > std::ostream & operator<<( std::ostream & os, const Forest<T> & for );
template< typename T> class Forest
{
friend std::ostream& operator<< <>( std::ostream&, const Forest<T> & );
//rest of class Forest
};
template< typename T >
std::ostream & operator<<( std::ostream& os, const Forest<T> & forest )
{
// implement
return os;
}
You would apply a similar technique to any other external function you wish to declare as a friend to your class, i.e.
Forwardly declare your class as a template
Forwardly declare the method as a template function
Make the function a friend using <> before the opening parentheses denoting the parameters
Implement the function after your class.
You have to provide a template arguments for all Forest parameters.
template<typename NODETYPE>
Forest<NODETYPE> operator+(Forest<NODETYPE>& f1, Forest<NODETYPE>& f2)
Also, consider making the arguments const references to make sure you do not manipulate them.
There are several questions on stackoverflow regarding friend function templates. The C++ FAQ also has a page on them that explains some basics.
You can define an operator+ template as follows:
template< class NodeType >
Forest<NodeType> operator+( Forest<NodeType> const& f1, Forest<NodeType> const& f2)
{
// Implementation.
}
Cheers & hth.,
Hey, I'm getting a linker error LNK2019: unresolved external symbol when trying to use an overloaded + operator. I'll show you snip-its from the class, and how I'm using it in main. If you need to see more, let me know, I'm just going to try and keep things concise.
/** vec.h **/
#ifndef __VEC_H_
#define __VEC_H_
#include <iostream>
#include <vector>
namespace xoor{
template<typename T>
class vec{
public:
inline friend vec<T> operator + (const vec<T>&, const vec<T>&);
inline const vec<T>& operator += (const vec<T>&);
private:
std::vector<T> m_index;
}; // Vec.
template<typename T>
vec<T>& operator + (const vec<T>& a, const vec<T>& b){
vec<T> product = a;
product += b;
return product;
} // Addition.
template<typename T>
const vec<T>& vec<T>::operator += (const vec<T>& v){
for (unsigned short i =0; i < m_index.size(); ++i){
if (i >= v.size())
break;
m_index[i] += v.getIndex()[i];
}
return * this;
} // Addition Compound.
} // xoor
#endif // __VEC_H_
Note that I've got [] overloaded as well, so I'm just accessing parts of m_index with it. getIndex() just returns m_index. And size() returns m_index.size()
/** main.cpp **/
#include <iostream>
#include "vec.h"
void testHook();
int main(){
testHook();
system("PAUSE");
return 0;
}
void testHook(){
using namespace xoor;
vec<double> vA(3); // passing 3 for 3 elements
vec<double> vB(3);
// v + v
std::cout << "\n\tA + B = ";
vec<double> vAB(3);
vAB = vA + vB; // PRODUCES THE LNK2019
vAB.print(std::cout); // Outputs the vec class to the console.
}
Error Message:
Error 1 error LNK2019: unresolved external symbol "class xoor::vec<double> __cdecl xoor::operator+(class xoor::vec<double> const &,class xoor::vec<double> const &)" (??Hxoor##YA?AV?$vec#N#0#ABV10#0#Z) referenced in function "void __cdecl testHook(void)" (?testHook##YAXXZ) main.obj
Update:
The following is now directly above the class definition. I continue to get the same linker error, as described above.
template<typename T>
class vec;
template<typename T>
vec<T> operator + (const vec<T>&, const vec<T>&);
Update 2: Solution.
The above update is incorrect. sbi's solution did work, I just failed to template the operator as follows.
template<typename T>
vec<T> operator +<T> (const vec<T>&, const vec<T>&);
sbi, and david were discussing why I was using friends in the first place. Initially I was using them, because you can not pass two parameters to an overloaded binary operator such as +, and immediate sought after friends as the solution. As it turns out, you can still use the binary operator quite easily with a single parameter. Here is the final solution.
// ...
template<typename T>
class vec{
public:
const vec<T> operator + (const vec<T>&, const vec<T>&)const;
// ...
}; // Vec.
template<typename T>
const vec<T> vec<T>::operator + (const vec<T>& v)const{
matrix<T> product = *this;
vec(product += v);
} // Addition.
Also, for anyone else reading this, its worth while to check out sbi's notes at the bottom of his answer. There are some things I've been doing that are superfluous.
Thanks for the help everyone. Happy coding.
In order to befriend a template, I think you'll need to declare that template before the class definition in which you want to befriend it. However, for this declaration to compile, you'll need to forward-declare the class template. So this should work:
template<typename T>
class vec;
template<typename T>
vec<T> operator + (vec<T>, const vec<T>&);
template<typename T>
class vec{
public:
friend vec<T> operator +<T> (vec<T>, const vec<T>&);
// ...
This befriends a specific instance of the operator+() function template, namely operator+<T>. (You can also befriend all instances of a template:
// no forward declarations necessary
template<typename T>
class some_class {
template<typename U>
friend void f(vec<U>&);
// ...
};
However, that's less often useful than the other one.)
Edit: A comment by David got me thinking (should've done this from the beginning!) and that lead to the discovery that the friend declaration is unnecessary. Your operator+ is only using one public member function of vec (operator+=) and thus doesn't need to be a friend of the class. So the above would simplify to
template<typename T>
class vec{
public:
// ...
};
template<typename T>
vec<T> operator + (vec<T> a, const vec<T>& b){
a += b;
return a;
}
Here's a few more notes:
operator+() (which you nicely implemented on top of operator+=(), BTW) should take its left argument per copy.
Don't declare functions as inline, define them so.
Have operator+=() return a non-const reference, because everybody expects f(m1+=m2) to work even if f() takes its argument as a non-const reference.
Inside of a class template, in most places you can omit the template parameter list when refering to the class. So you can say vec& operator += (const vec&);. (You cannot do this outside of the template, though - for example, when defining that operator outside of the class.)
A std::vector's index type is spelled std::vector<blah>::size_type, not unsigned short.
The return type here:
inline friend vec<T> operator + (const vec<T>&, const vec<T>&);
Does not match here:
template<typename T>
vec<T>& operator + (const vec<T>& a, const vec<T>& b){
vec<T> product = a;
product += b;
return product;
} // Addition.