For example, I have 2 structures: a 2D vector and a 3D vector with defined += operators:
struct Vector2
{
double x;
double y;
....
Vector2& operator+=(const Vector2& vector);
....
};
struct Vector3
{
double x;
double y;
double z;
....
Vector3& operator+=(const Vector3& vector);
....
};
It is trivial to implement '+' operators for these structures using the corresponding '+=' operators:
Vector2 operator+(const Vector2& vector1, const Vector2& vector2)
{
Vector2 result(vector1);
result += vector2;
return result;
}
Vector3 operator+(const Vector3& vector1, const Vector3& vector2)
{
Vector3 result(vector1);
result += vector2;
return result;
}
I'd like to unify these 2 functions and replace them with one template function:
template <class T>
T operator+(const T& vector1, const T& vector2)
{
T result(vector1);
result += vector2;
return result;
}
But this function is so general that it makes operator+ ambiguous for other classes.
I tried to make this template applicable only for Vector2 and Vector3 structs using custom type traits and static_assert:
template <class T>
T operator+(const T& vector1, const T& vector2)
{
static_assert(suitable_type_for_this_function<T>::value, "Unsupported type!");
...
}
But it does not hide declaration of the template operator for other classes. Therefore this approach again leads to ambiguity.
How can I implement such a unified operator+, but define it only for these 2 specific types?
template<class D>
struct add_using_increment {
using Self=add_using_increment<D>;
friend D operator+(Self&& lhs, Self const& rhs){
lhs+=rhs;
return std::move(lhs.self());
}
friend D operator+(Self const& lhs, Self const& rhs){
return D(lhs.self())+rhs;
}
private:
D&self(){ return *static_cast<D*>(this); }
D const&self()const{ return *static_cast<D const*>(this); }
};
Now just do this:
struct Vector2:add_using_increment<Vector2>
Altenratively you can use SFINAE to restrict your template argument to (A) being one of a fixed set, (B) having a void increment( lhs&, rhs const& ) function defined on it, (C) having a += defined on it.
(C) is too greedy.
You can also use boost.operators which is an industrial strength version of my add_using_increment.
You can apply SFINAE, use std::enable_if with std::is_same to constrain the types allowed on T.
template <class T>
std::enable_if_t<std::is_same_v<T, Vector2> || std::is_same_v<T, Vector3>, T>
operator+(const T& vector1, const T& vector2);
Related
This Vec template supports several functions such as multiplying a vector by scalar and adding vector to another vector.
The thing that is confusing me is that why the overloading of the second operator* is outside of the class template?
The operator* which is declared in the class overloads vectorXscalar
The one declared outside supports scalarXvector
template <class T>
class Vec {
public:
typename list<T>::const_iterator begin() const {
return vals_.begin();
}
typename list<T>::const_iterator end() const {
return vals_.end();
}
Vec() {};
Vec(const T& el);
void push_back(T el);
unsigned int size() const;
Vec operator+(const Vec& rhs) const;
Vec operator*(const T& rhs) const; //here
T& operator[](unsigned int ind);
const T& operator[](unsigned int ind) const;
Vec operator,(const Vec& rhs) const;
Vec operator[](const Vec<unsigned int>& ind) const;
template <class Compare>
void sort(Compare comp) {
vals_.sort(comp);
}
protected:
list<T> vals_;
};
template <class T>
Vec<T> operator*(const T& lhs, const Vec<T>& rhs); //and here!
template <class T>
ostream& operator<<(ostream& ro, const Vec<T>& v);
The operator* declared inside the template class could equally be written outside the class as
template <class T>
Vec<T> operator*(const Vec<T>& lhs, const T& rhs);
It can be written inside the class with a single argument (representing the rhs) because there is the implied *this argument used as the lhs of the operator.
The difference with the operator* defined outside the class is that the lhs of the operator is a template type. This allows the arguments to be supplied either way around when using the operator.
You are allowed to define the operator outside of a class with any arbitrary lhs and rhs types, but within the class are restricted to only varying the rhs. The compiler would select the best match of any defined operator* given the argument types.
I have a template class typically instantiated by <double>.
My header has something like:
template <typename T> class F;
// Non-member functions
template <typename T> const F<T> operator*(F<T> lhs, const F<T>& rhs);
template <typename T> const F<T> operator*(const F<T>& lhs, const T& rhs);
template <typename T>
class F
{
// blah blah
F<T>& operator*=(const F<T>& rhs);
F<T>& operator*=(const T& rhs_scalar);
// blah
friend const F<T> operator*(const F<T>& lhs, const T& rhs) { return F(lhs) *= rhs; }
friend const F<T> operator*(const T& lhs, const F<T>& rhs) { return F(rhs) *= lhs; }
};
In my .cpp file, I have something like:
#include "F.H"
// lots of template<typename T> returntype F<T>::function(args){ body }
template <typename T>
F<T>& F<T>::operator*=(const F<T>& rhs)
{
// check sizes, etc
// do multiplication
return *this;
}
template <typename T>
F<T>& F<T>::operator*=(const T& rhs_scalar)
{
for(auto &lhs : field_) // field_ is a vector holding values
{
lhs *= rhs_scalar;
}
return *this;
}
// Non-member parts
template <typename T> operator*(F<T> lhs, const F<T>& rhs)
{ lhs *= rhs; return lhs; }
template <typename T> operator*(const F<T>& lhs, const T& rhs)
{ return F<T>(lhs) *= rhs; }
template class F<double>;
template const F<double> operator*<double>(F<double>, const F<double>&);
This compiles and runs ok, and allows things like:
F<double> test(..);
test *= 2.5; test *= 10; test /= 2.5; test /= 10; // and so on
The question I have is: Can I reduce the number of declarations and definitions of my operators, whilst retaining the ability to implicitly promote an int to a double, etc? Can I rearrange the code so that the friend .. operator*(..) bodies are defined outside of the header file? (I suspect this would involve more specific instantiations in one or both of the header and the cpp file)
(Side note: how? Scott Meyer's Item 46 in 'Effective C++' describes implicit parameter conversion, but it seems like that describes allowing the construction of a temporary object to allow (in that case) Rational(int) * Rational_object_already_created;)
Can I reduce the number of declarations and definitions of my operators, whilst retaining the ability to implicitly promote an int to a double, etc?
You can do that by providing a converting constructor.
template <typename T2>
F(F<T2> const& f2 ) {...}
It seems strange but this simple code works with int instead of T, and does not work with template T.
template <typename T>
class Polynomial {
public:
Polynomial (T i) {}
Polynomial& operator+= (const Polynomial& rhs) {
return *this;
}
};
template <typename T>
const Polynomial<T> operator+ (Polynomial<T> lhs_copy, const Polynomial<T>& rhs) {
return lhs_copy += rhs;
}
Polynomial<int> x (1), y = x + 2; // no match for 'operator+' in 'x + 2'
Implicit conversion don't apply during template argument deduction, you might render your function friend(so that the type is known):
template <typename T>
class Polynomial {
public:
Polynomial (T i) {};
Polynomial& operator+= (const Polynomial& rhs) { return *this; };
friend Polynomial operator+ (Polynomial lhs, const Polynomial& rhs) {
return lhs+=rhs;
}
};
Also related: C++ addition overload ambiguity
I have a template class for which I'm overloading operator+, but need it to potentially return a different data type than what the class is instantiated for. For example, the following snippet performs the standard mathematical definition of either vector*vector (inner product), vector*scalar, or scalar*vector. To be specific, let's say I have a Vector<int> and the scalar is of type double -- I want to return a double from the "vector*scalar" operator+ function.
I'm pretty sure I'm missing some template<class T> statements for the friend functions(?), but this snippet isn't meant to compile.
template<class T>
class Vector
{
private:
std::vector<T> base;
public:
friend Vector operator*(const Vector& lhs, const Vector& rhs); // inner product
Vector<T> operator*(const T scalar); // vector*scalar
friend Vector operator*(const T scalar, const Vector& rhs); // scalar*vector
};
template<class T>
Vector<T> operator*(const Vector<T>& lhs, const Vector<T>& rhs) // inner product
{
assert( lhs.base.size() == rhs.base.size() );
Vector result;
result.base.reserve(lhs.base.size());
std::transform( lhs.base.begin(), lhs.base.end(), rhs.base.begin(), std::back_inserter(result.base), std::multiplies<T>() );
return result;
}
template<class T>
Vector<T> Vector<T>::operator*(const T scalar) // vector*scalar
{
Vector result;
result.base.reserve(base.size());
std::transform( base.begin(), base.end(), std::back_inserter(result.base), std::bind1st(std::multiplies<T>(), scalar) );
return result;
}
template<class T>
Vector<T> operator*(const T scalar, const Vector<T>& rhs) // scalar*vector
{
Vector result;
result.base.reserve(rhs.base.size());
std::transform( rhs.base.begin(), rhs.base.end(), std::back_inserter(result.base), std::bind1st(std::multiplies<T>(), scalar) );
return result;
}
I guess what you want is to return a Vector with the value type being the type returned by the per-component operation, which is not necessarily the type of the scalar.
For example:
Vector<int> * int -> Vector<int>
Vector<int> * double -> Vector<double>
Vector<double> * int -> Vector<double>
Vector<char> * float -> Vector<float>
etc.
For this, you should define the two input types separately, let's say T1 and T2 (and one or two of the operands is a Vector of it). You don't want to simply use the scalar type (for vector * scalar, or scalar * vector operation) as the result, otherwise it might be converted (see my 3rd example: The result would then be Vector<int>.
The above can be done using decltype to find the third (result) type.
For simplicity, define the operator as a non-member:
template<typename T1, typename T2, typename T3 = decltype(std::declval<T1>() * std::declval<T2>())>
Vector<T3> operator*(const Vector<T1>& lhs, const T2 & scalar) // inner product
{
Vector<T3> result;
//...
return result;
}
The interesting part is
T3 = decltype(std::declval<T1>() * std::declval<T2>())
Here, we find the type T3 using the other two types T1 and T2. First, we construct two values with unimportant value (the std::declval function is a helper function returning the type given as a template parameter). Then we multiply those values, but again the result is unimportant; we're only interested in the type. That's what the third part does: decltype gives you the type of the expression (without evaluating it).
The other operators can be implemented analogous.
In order to make those operators friends, you need the syntax
template<...> friend ...
as seen in Danvil's answer.
The friend declaration should look like this:
template<class S>
class Vector
{
private:
std::vector<S> base;
public:
template<class T> friend T operator*(const Vector<T>& lhs, const Vector<T>& rhs); // inner product
template<class T> friend Vector<T> operator*(const T scalar); // vector*scalar
template<class T> friend Vector<T> operator*(const T scalar, const Vector<T>& rhs); // scalar*vector
};
And the rest of the code like this:
template<class T>
T operator*(const Vector<T>& lhs, const Vector<T>& rhs) // inner product
{
assert( lhs.base.size() == rhs.base.size() );
Vector<T> result;
result.base.reserve(lhs.base.size());
std::transform( lhs.base.begin(), lhs.base.end(), rhs.base.begin(), std::back_inserter(result.base), std::multiplies<T>() );
return result;
}
template<class T>
Vector<T> operator*(const Vector<T>& lhs, const T scalar) // vector*scalar
{
return scalar*lhs;
}
template<class T>
Vector<T> operator*(const T scalar, const Vector<T>& rhs) // scalar*vector
{
Vector<T> result;
result.base.reserve(rhs.base.size());
std::transform( rhs.base.begin(), rhs.base.end(), std::back_inserter(result.base), std::bind1st(std::multiplies<T>(), scalar) );
return result;
}
You can add more template parameters as such:
template<class T, class S>
Vector<S> Vector<T>::operator*(const S scalar)
and make sure you use S for the scalar type and T for the vector element type in the correct places in the function body.
I don't understand this link error.
I have 2 classes:
#include "Vector3.h"
#include "Quaternion.h"
template<typename T>
class Point3 final
{
public:
constexpr Point3(const Vector3<T>& vec)
: x(vec.x), y(vec.y), z(vec.z)
{}
constexpr operator const Vector3<T>() const
{
// It is the equivalent of Vector3 = Point3 - Origin
return Vector3<T>(x, y, z);
}
constexpr operator Vector3<T>() const
{
// It is the equivalent of Vector3 = Point3 - Origin
return Vector3<T>(x, y, z);
}
T x = T(0);
T y = T(0);
T z = T(0);
friend Vector3<T>;
friend Quaternion<T>;
friend Vector3<T> operator*( const Quaternion<T>& lhs, const Vector3<T>& rhs);
friend Vector3<T> operator*( Vector3<T> lhs, const Vector3<T>& rhs);
};
typedef Point3<Float32> Point3f;
and
template<typename T>
class Vector3 final
{
public:
constexpr Vector3()
{}
constexpr Vector3(T _x, T _y, T _z)
: x(_x), y(_y), z(_z)
{}
T x = T(0);
T y = T(0);
T z = T(0);
};
typedef Vector3<Float32> Vector3f;
I also have a Quaternion class the detail are irrelevant i beleive but this class has a non member operator*:
template<typename T>
Vector3<T> operator*( const Quaternion<T>& lhs, const Vector3<T>& rhs)
{
// nVidia SDK implementation
Vector3<T> qvec(lhs.x, lhs.y, lhs.z);
Vector3<T> uv = cross(qvec, rhs) * T(2.0) * lhs.w; //uv = qvec ^ v;
Vector3<T> uuv = cross(qvec, uv) * T(2.0); //uuv = qvec ^ uv;
return rhs + uv + uuv;
}
Now those line produce a link error, but why?
Math::Point3<Float32> pt = -Math::Point3<Float32>::UNIT_Z;
Math::Vector3<Float32> vec = orientation_*pt; // link error here (orientation is a Quaternion<Float32>)
//Math::Vector3<Float32> vec = orientation_*Math::Vector3<Float32>(pt); // this solve the link error.
Here is the link error
Undefined symbols for architecture x86_64:
Math::operator*(Math::Quaternion<float> const&, Math::Vector3<float> const&), referenced from:
GfxObject::Procedural::BoxGenerator::addToTriangleBuffer(GfxObject::Procedural::TriangleBuffer&) const in ProceduralBoxGenerator.o
Update
I found 2 question that are really close to this but the problem relies in the differences.
in:
question 1 and
question 2
But in my case I need to convert between 2 templates classes instead of the same class but 2 instantions. I hope this will help!
Try making sure the compiler knows your friend declaration is supposed to be a template specialization, not a declaration of a brand new non-template function:
friend Vector3<T> operator* <> (const Quaternion<T>& lhs, const Vector3<T>& rhs);
This common mistake is discussed in the C++ FAQ here.
Starting with an SSCCE:
template<typename T> class Quaternion { };
template<typename T> class Vector3 { };
template<typename T> class Point3 {
public:
operator Vector3<T>() const { return Vector3<T>(); }
friend Vector3<T> operator*( const Quaternion<T>& lhs, const Vector3<T>& rhs);
};
template<typename T>
Vector3<T> operator*(const Quaternion<T>& lhs, const Vector3<T>& rhs) { }
int main() {
Quaternion<float> orientation_;
Point3<float> pt;
Vector3<float> vec = orientation_*pt;
return 0;
}
Compiling that with gcc 4.7 I get the following:
x.cc:6:79: warning: friend declaration ‘Vector3<T> operator*(const Quaternion<T>&,
const Vector3<T>&)’ declares a non-template function
[-Wnon-template-friend]
x.cc:6:79: note: (if this is not what you intended, make sure the function template
has already been declared and add <> after the function name here)
Undefined symbols for architecture x86_64:
"operator*(Quaternion<float> const&, Vector3<float> const&)", referenced from:
_main in ccKgI7Ru.o
This points out the problem: you are declaring a friend function, not a friend template. To fix this, you have to do two things: make sure the template declaration preceedes this friendship line, and add angle brackets:
template<typename T>
Vector3<T> operator*(const Quaternion<T>& lhs, const Vector3<T>& rhs) { }
template<typename T> class Point3 {
public:
operator Vector3<T>() const { return Vector3<T>(); }
friend Vector3<T> operator*<>(const Quaternion<T>& lhs, const Vector3<T>& rhs);
};
This will turn the linker error into a compiler error:
error: no match for ‘operator*’ in ‘orientation_ * pt’
note: candidate is:
note: template<class T> Vector3<T> operator*(const Quaternion<T>&, const Vector3<T>&)
note: template argument deduction/substitution failed:
note: ‘Point3<float>’ is not derived from ‘const Vector3<T>’
Which makes sense: declaring a friend is a statement about who may access what data; it does not help a bit in automatic type conversions for template resolution. So I suggest the following instead:
template<typename T> class Point3 {
public:
operator Vector3<T>() const { return Vector3<T>(); }
friend Vector3<T> operator*(const Quaternion<T>& lhs, const Point3& rhs) {
return lhs * Vector3<T>(rhs);
}
};
This declares a new inline friend operator, which will explicitely do the cast you had intended.
Actually to make it work i have to give a body to the friend declared function in the Point class. I wanted to do like item 46 of Effective C++ (3rd edition) from Scott Meyers. like in this question, link.
The key is that the function inside have to have a body. so the class Point3 now become (I have stripped some useless code like MvG did, thanks.
template<typename T> class Point3 {
public:
operator Vector3<T>() const { return Vector3<T>(); }
friend Vector3<T> operator*( const Quaternion<T>& lhs, const Vector3<T>& rhs)
{
return lhs*rhs;
}
};
This make everything compiles and link.
lhsrhs will call the operator defined in Quaternion.h ( that is included in the header file of Point3).
What i don't understand is why i don't have duplicated symbol.
To me the friend operator* inside the Point3 class and the operator* defined in the Quaternion.h header file are the same signature and yet it compile and links.