I have simple class:
#include <utility>
template<class T, class... Ts>
T make(const Ts&... args) //generic class maker
{
return T(args...);
}
template<class T>
class A
{
public:
A(void) : x_(T()), y_(T()) {}
explicit A(int x) : x_(x), y_(x) {}
A(int x, int y) : x_(x), y_(y) {}
A(const A& other) : x_(other.x_), y_(other.y_) {}
A(A&& temp) : x_(std::move(temp.x_)), y_(std::move(temp.y_)) {}
auto& operator =(A other);
auto& operator +=(const A& other);
auto operator + (const A& other) const;
private:
T x_;
T y_;
};
template<class T>
auto& A<T>::operator =(A<T> other)
{
std::swap(*this, other); return *this;
}
template<class T>
auto& A<T>::operator+=(const A<T>& other)
{
x_ += other.x_;
y_ += other.y_;
return *this;
}
template<class T>
auto A<T>::operator+(const A<T>& other) const
{
return make<A<T>>(*this) += other;
}
int main()
{
A<int> first(1);
auto second = A<int>(2,2);
auto third = make<A<int>>(second+first);
auto fourth = make<A<int>>(4);
auto fifth = make<A<int>>(5,5);
}
But when I try to deduce operator+ type from *this, I get strange errors I don't expect:
template<class T>
auto A<T>::operator+(const A<T>& other) const
{
return make<typename std::remove_cv<decltype(*this)>::type>(*this) += other;
}
int main()
{
auto solo = A<int>();
solo + solo;
}
Errors:
error: passing 'const A<int>' as 'this' argument of 'auto& A<T>::operator+=(const A<T>&)
[with T = int]' discards qualifiers [-fpermissive]
return make<typename std::remove_cv<decltype(*this)>::type>(*this) += other;
^
error: use of 'auto& A<T>::operator+=(const A<T>&) [with T = int]' before deduction
of 'auto'
error: invalid use of 'auto'
return make<typename std::remove_cv<decltype(*this)>::type>(*this) += other;
^
error: invalid use of 'auto'
If I'm right, make(...)
should create new object (which should be free of cv), so why do I get discards qualifiers [-fpermissive]
error?
Aucun commentaire:
Enregistrer un commentaire