questions about the implementation of Complex in c++'s library? - c++

I find Complex's operator+ in MSVC return non-const Complex
_TMPLT(_Ty) inline
_CMPLX(_Ty) operator+(const _Ty& _Left,
const _CMPLX(_Ty)& _Right)
{ // add complex to real
_CMPLX(_Ty) _Tmp(_Left);
return (_Tmp += _Right);
}
Also, in cppreference, it is also non-const
template< class T >
complex<T> operator+( const complex<T>& lhs, const complex<T>& rhs);
(1)
template< class T >
complex<T> operator+( const complex<T>& lhs, const T& rhs);
(2)
template< class T >
complex<T> operator+( const T& lhs, const complex<T>& rhs);
(3)
template< class T >
complex<T> operator-( const complex<T>& lhs, const complex<T>& rhs);
(4)
template< class T >
complex<T> operator-( const complex<T>& lhs, const T& rhs);
(5)
template< class T >
complex<T> operator-( const T& lhs, const complex<T>& rhs);
(6)
template< class T >
complex<T> operator*( const complex<T>& lhs, const complex<T>& rhs);
(7)
template< class T >
complex<T> operator*( const complex<T>& lhs, const T& rhs);
(8)
template< class T >
complex<T> operator*( const T& lhs, const complex<T>& rhs);
(9)
template< class T >
complex<T> operator/( const complex<T>& lhs, const complex<T>& rhs);
(10)
template< class T >
complex<T> operator/( const complex<T>& lhs, const T& rhs);
(11)
template< class T >
complex<T> operator/( const T& lhs, const complex<T>& rhs);
Then someone maintains that it should be const.
However, I just can't think of such a situation which leads to the necessity of non-const.
Can someone show me such a situation? Thanks

You misunderstood the question and the answer you linked.
The answer doesn't say anything about the return value of a function. the answer talks about parameters passed to a function, and correctly suggests that parameters should be passed as constant references and constant pointers if that function doesn't mutate these parameters
Parameters should be passed as const references if that function doesn't mutate them
function should be declared as const if that function does not mutate the object it was called from.
there's is no reason for an operator + (const T& a , const T& b) to return const object, doing so may prevent important optimizations.

Related

C++ template functions

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.

Exporting templated inline functions - definition of function dllimport not allowed

I'm trying to implement math library but I'm stuck on exporting. I have a template class for 2-dimensional vector:
vector2.h:
template <typename T>
class GE_API Vector2
{
public:
T x;
T y;
// Indexation
T& operator [] (const size_t i);
const T& operator [] (const size_t i) const;
bool operator == (const Vector2& v) const;
bool operator != (const Vector2& v) const;
// Negation
const Vector2 operator - () const;
// Assignement
const Vector2& operator = (const Vector2& v);
const Vector2& operator += (const Vector2& v);
const Vector2& operator -= (const Vector2& v);
template <typename S>
const Vector2& operator *= (const S& s);
template <typename S>
const Vector2& operator /= (const S& s);
const Vector2 operator + (const Vector2& v) const;
const Vector2 operator + (const T& s) const;
const Vector2 operator - (const Vector2& v) const;
const Vector2 operator - (const T& s) const;
template <typename S>
const Vector2 operator * (const S& s) const;
const Vector2 operator * (const Vector2& v) const;
template <typename S>
const Vector2 operator / (const S& s) const;
const Vector2 operator / (const Vector2& v) const;
};
template <typename T>
GE_API const T dot(const Vector2<T>& a, const Vector2<T>& b);
template <typename T>
GE_API const T length(const Vector2<T>& v);
//..and other functionality
#include <vector2.inl>
Definitions of operators and functions are in separate file vector2.inl which is included in header file. GE_API is standard dllimport/export macro. Problem is that when I try to export this class and functions defined in vector2.h header file I'm getting errors on definitions of operators that definition of dllimport function is not allowed. Why is that and how to fix this?
I think in this case you don't need to specify dllimport/export for your class.
Because all source code will be avaliable to the user and only anoe thing that he heeds is to include vactor2.h header into his project.

std::optional specialization for reference types

Why std::optional (std::experimental::optional in libc++ at the moment) does not have specialization for reference types (compared with boost::optional)?
I think it would be very useful option.
Is there some object with reference to maybe already existing object semantics in STL?
When n3406 (revision #2 of the proposal) was discussed, some committee members were uncomfortable with optional references. In n3527 (revision #3), the authors decided to make optional references an auxiliary proposal, to increase the chances of getting optional values approved and put into what became C++14. While optional didn't quite make it into C++14 for various other reasons, the committee did not reject optional references and is free to add optional references in the future should someone propose it.
The main problem with std::optional <T&> is — what should optRef = obj do in the following case:
optional<T&> optRef;
…;
T obj {…};
optRef = obj; // <-- here!
Variants:
Always rebind — (&optRef)->~optional(); new (&optRef) optional<T&>(obj).
Assign through — *optRef = obj (UB when !optRef before).
Bind if empty, assign through otherwise — if (optRef) {do1;} else {do2;}.
No assignment operator — compile-time error "trying to use a deleted operator".
Pros of every variant:
Always rebind (chosen by boost::optional and n1878):
Consistency between the cases when !optRef and optRef.has_value() — post-condition &*optRef == &obj is always met.
Consistency with usual optional<T> in the following aspect: for usual optional<T>, if T::operator= is defined to act as destroying and constructing (and some argue that it must be nothing more than optimization for destroying-and-constructing), opt = … de facto acts similarly like (&opt)->~optional(); new (&opt) optional<T&>(obj).
Assign through:
Consistency with pure T& in the following aspect: for pure T&, ref = … assigns through (not rebinds the ref).
Consistency with usual optional<T> in the following aspect: for usual optional<T>, when opt.has_value(), opt = … is required to assign through, not to destroy-and-construct (see template <class U> optional<T>& optional<T>::operator=(U&& v) in n3672 and on cppreference.com).
Consistency with usual optional<T> in the following aspect: both haveoperator= defined at least somehow.
Bind if empty, assign through otherwise — I see no real benefits, IMHO this variant arises only when proponents of #1 argue with proponents of #2, however formally it's even more consistent with the letter of requirements for template <class U> optional<T>& optional<T>::operator=(U&& v) (but not with the spirit, IMHO).
No assignment operator (chosen by n3406):
Consistency with pure T& in the following aspect: pure T& doesn't allow to rebind itself.
No ambiguous behavior.
See also:
Let’s Talk about std::optional<T&> and optional references.
Why Optional References Didn’t Make It In C++17.
There is indeed something that has reference to maybe existing object semantics. It is called a (const) pointer. A plain old non-owning pointer. There are three differences between references and pointers:
Pointers can be null, references can not. This is exactly the difference you want to circumvent with std::optional.
Pointers can be redirected to point to something else. Make it const, and that difference disappears as well.
References need not be dereferenced by -> or *. This is pure syntactic sugar and possible because of 1. And the pointer syntax (dereferencing and convertible to bool) is exactly what std::optional provides for accessing the value and testing its presence.
Update:
optional is a container for values. Like other containers (vector, for example) it is not designed to contain references. If you want an optional reference, use a pointer, or if you indeed need an interface with a similar syntax to std::optional, create a small (and trivial) wrapper for pointers.
Update2: As for the question why there is no such specialization: because the committee simply did opt it out. The rationale might be found somewhere in the papers. It possibly is because they considered pointers to be sufficient.
IMHO it is very okay to make std::optional<T&> available. However there is a subtle issue about templates. Template parameters can become tricky to deal with if there are references.
Just as the way we solved the problem of references in template parameters, we can use a std::reference_wrapper to circumvent the absence of std::optional<T&>. So now it becomes std::optional<std::reference_wrapper<T>>. However I recommend against this use because 1) it is way too verbose to both write the signature (trailing return type saves us a bit) and the use of it (we have to call std::reference_wrapper<T>::get() to get the real reference), and 2) most programmers have already been tortured by pointers so that it is like an instinctive reaction that when they receive a pointer they test first whether it is null so it is not quite much an issue now.
If I would hazard a guess, it would be because of this sentence in the specification of std::experimental::optional. (Section 5.2, p1)
A program that necessitates the instantiation of template optional
for a reference type, or for possibly cv-qualified types in_place_t or
nullopt_t is ill-formed.
I stumbled upon this several times and I finally decided to implement my solution that doesn't depend on boost. For reference types it disables assignment operator and doesn't allow for comparison of pointers or r-values. It is based on a similar work I did some time ago, and it uses nullptr instead of nullopt to signal absence of value. For this reason, the type is called nullable and compilation is disabled for pointer types (they have nullptr anyway). Please let me know if you find any obvious or any non-obvious problem with it.
#ifndef COMMON_NULLABLE_H
#define COMMON_NULLABLE_H
#pragma once
#include <cstddef>
#include <stdexcept>
#include <type_traits>
namespace COMMON_NAMESPACE
{
class bad_nullable_access : public std::runtime_error
{
public:
bad_nullable_access()
: std::runtime_error("nullable object doesn't have a value") { }
};
/**
* Alternative to std::optional that supports reference (but not pointer) types
*/
template <typename T, typename = std::enable_if_t<!std::is_pointer<T>::value>>
class nullable final
{
public:
nullable()
: m_hasValue(false), m_value{ } { }
nullable(T value)
: m_hasValue(true), m_value(std::move(value)) { }
nullable(std::nullptr_t)
: m_hasValue(false), m_value{ } { }
nullable(const nullable& value) = default;
nullable& operator=(const nullable& value) = default;
nullable& operator=(T value)
{
m_hasValue = true;
m_value = std::move(value);
return *this;
}
nullable& operator=(std::nullptr_t)
{
m_hasValue = false;
m_value = { };
return *this;
}
const T& value() const
{
if (!m_hasValue)
throw bad_nullable_access();
return m_value;
}
T& value()
{
if (!m_hasValue)
throw bad_nullable_access();
return m_value;
}
bool has_value() const { return m_hasValue; }
const T* operator->() const { return &m_value; }
T* operator->() { return &m_value; }
const T& operator*() const { return m_value; }
T& operator*() { return m_value; }
public:
template <typename T2>
friend bool operator==(const nullable<T2>& lhs, const nullable<T2>& rhs);
template <typename T2>
friend bool operator!=(const nullable<T2>& lhs, const nullable<T2>& rhs);
template <typename T2>
friend bool operator==(const nullable<std::decay_t<T2>>& lhs, const nullable<T2&>& rhs);
template <typename T2>
friend bool operator!=(const nullable<std::decay_t<T2>>& lhs, const nullable<T2&>& rhs);
template <typename T2>
friend bool operator==(const nullable<T2&>& lhs, const nullable<std::decay_t<T2>>& rhs);
template <typename T2>
friend bool operator!=(const nullable<T2&>& lhs, const nullable<std::decay_t<T2>>& rhs);
template <typename T2>
friend bool operator==(const nullable<T2>& lhs, const T2& rhs);
template <typename T2>
friend bool operator==(const T2& lhs, const nullable<T2>& rhs);
template <typename T2>
friend bool operator==(const nullable<T2>& lhs, std::nullptr_t);
template <typename T2>
friend bool operator!=(const nullable<T2>& lhs, const T2& rhs);
template <typename T2>
friend bool operator!=(const T2& lhs, const nullable<T2>& rhs);
template <typename T2>
friend bool operator==(std::nullptr_t, const nullable<T2>& rhs);
template <typename T2>
friend bool operator!=(const nullable<T2>& lhs, std::nullptr_t);
template <typename T2>
friend bool operator!=(std::nullptr_t, const nullable<T2>& rhs);
private:
bool m_hasValue;
T m_value;
};
// Template spacialization for references
template <typename T>
class nullable<T&> final
{
public:
nullable()
: m_hasValue(false), m_value{ } { }
nullable(T& value)
: m_hasValue(true), m_value(&value) { }
nullable(std::nullptr_t)
: m_hasValue(false), m_value{ } { }
nullable(const nullable& value) = default;
nullable& operator=(const nullable& value) = default;
const T& value() const
{
if (!m_hasValue)
throw bad_nullable_access();
return *m_value;
}
T& value()
{
if (!m_hasValue)
throw bad_nullable_access();
return *m_value;
}
bool has_value() const { return m_hasValue; }
const T* operator->() const { return m_value; }
T* operator->() { return m_value; }
const T& operator*() const { return *m_value; }
T& operator*() { return *m_value; }
public:
template <typename T2>
friend bool operator==(const nullable<std::decay_t<T2>>& lhs, const nullable<T2&>& rhs);
template <typename T2>
friend bool operator!=(const nullable<std::decay_t<T2>>& lhs, const nullable<T2&>& rhs);
template <typename T2>
friend bool operator==(const nullable<T2&>& lhs, const nullable<std::decay_t<T2>>& rhs);
template <typename T2>
friend bool operator!=(const nullable<T2&>& lhs, const nullable<std::decay_t<T2>>& rhs);
template <typename T2>
friend bool operator==(const nullable<T2&>& lhs, const nullable<T2&>& rhs);
template <typename T2>
friend bool operator!=(const nullable<T2&>& lhs, const nullable<T2&>& rhs);
template <typename T2>
friend bool operator==(const nullable<T2&>& lhs, const std::decay_t<T2>& rhs);
template <typename T2>
friend bool operator!=(const nullable<T2&>& lhs, const std::decay_t<T2>& rhs);
template <typename T2>
friend bool operator==(const std::decay_t<T2>& lhs, const nullable<T2&>& rhs);
template <typename T2>
friend bool operator!=(const std::decay_t<T2>& lhs, const nullable<T2&>& rhs);
template <typename T2>
friend bool operator==(const nullable<T2>& lhs, std::nullptr_t);
template <typename T2>
friend bool operator==(std::nullptr_t, const nullable<T2>& rhs);
template <typename T2>
friend bool operator!=(const nullable<T2>& lhs, std::nullptr_t);
template <typename T2>
friend bool operator!=(std::nullptr_t, const nullable<T2>& rhs);
private:
bool m_hasValue;
T* m_value;
};
template <typename T>
using nullableref = nullable<T&>;
template <typename T2>
bool operator==(const nullable<T2>& lhs, const nullable<T2>& rhs)
{
if (lhs.m_hasValue != rhs.m_hasValue)
return false;
if (lhs.m_hasValue)
return lhs.m_value == rhs.m_value;
else
return true;
}
template <typename T2>
bool operator!=(const nullable<T2>& lhs, const nullable<T2>& rhs)
{
if (lhs.m_hasValue != rhs.m_hasValue)
return true;
if (lhs.m_hasValue)
return lhs.m_value != rhs.m_value;
else
return false;
}
template <typename T2>
bool operator==(const nullable<std::decay_t<T2>>& lhs, const nullable<T2&>& rhs)
{
if (lhs.m_hasValue != rhs.m_hasValue)
return true;
if (lhs.m_hasValue)
return lhs.m_value != *rhs.m_value;
else
return false;
}
template <typename T2>
bool operator!=(const nullable<std::decay_t<T2>>& lhs, const nullable<T2&>& rhs)
{
if (lhs.m_hasValue != rhs.m_hasValue)
return true;
if (lhs.m_hasValue)
return lhs.m_value != *rhs.m_value;
else
return false;
}
template <typename T2>
bool operator==(const nullable<T2&>& lhs, const nullable<std::decay_t<T2>>& rhs)
{
if (lhs.m_hasValue != rhs.m_hasValue)
return false;
if (lhs.m_hasValue)
return *lhs.m_value == rhs.m_value;
else
return true;
}
template <typename T2>
bool operator!=(const nullable<T2&>& lhs, const nullable<std::decay_t<T2>>& rhs)
{
if (lhs.m_hasValue != rhs.m_hasValue)
return true;
if (lhs.m_hasValue)
return *lhs.m_value != rhs.m_value;
else
return false;
}
template <typename T2>
bool operator==(const nullable<T2&>& lhs, const nullable<T2&>& rhs)
{
if (lhs.m_hasValue != rhs.m_hasValue)
return false;
if (lhs.m_hasValue)
return *lhs.m_value == *rhs.m_value;
else
return true;
}
template <typename T2>
bool operator!=(const nullable<T2&>& lhs, const nullable<T2&>& rhs)
{
if (lhs.m_hasValue != rhs.m_hasValue)
return true;
if (lhs.m_hasValue)
return *lhs.m_value != *rhs.m_value;
else
return false;
}
template <typename T2>
bool operator==(const nullable<T2&>& lhs, const std::decay_t<T2>& rhs)
{
if (!lhs.m_hasValue)
return false;
return *lhs.m_value == rhs;
}
template <typename T2>
bool operator!=(const nullable<T2&>& lhs, const std::decay_t<T2>& rhs)
{
if (!lhs.m_hasValue)
return true;
return *lhs.m_value != rhs;
}
template <typename T2>
bool operator==(const std::decay_t<T2>& lhs, const nullable<T2&>& rhs)
{
if (!rhs.m_hasValue)
return false;
return lhs == *rhs.m_value;
}
template <typename T2>
bool operator!=(const std::decay_t<T2>& lhs, const nullable<T2&>& rhs)
{
if (!rhs.m_hasValue)
return true;
return lhs != *rhs.m_value;
}
template <typename T2>
bool operator==(const nullable<T2>& lhs, const T2& rhs)
{
if (!lhs.m_hasValue)
return false;
return lhs.m_value == rhs;
}
template <typename T2>
bool operator!=(const nullable<T2>& lhs, const T2& rhs)
{
if (!lhs.m_hasValue)
return true;
return lhs.m_value != rhs;
}
template <typename T2>
bool operator==(const T2& lhs, const nullable<T2>& rhs)
{
if (!rhs.m_hasValue)
return false;
return lhs == rhs.m_value;
}
template <typename T2>
bool operator!=(const T2& lhs, const nullable<T2>& rhs)
{
if (!rhs.m_hasValue)
return true;
return lhs != rhs.m_value;
}
template <typename T2>
bool operator==(const nullable<T2>& lhs, std::nullptr_t)
{
return !lhs.m_hasValue;
}
template <typename T2>
bool operator!=(const nullable<T2>& lhs, std::nullptr_t)
{
return lhs.m_hasValue;
}
template <typename T2>
bool operator==(std::nullptr_t, const nullable<T2>& rhs)
{
return !rhs.m_hasValue;
}
template <typename T2>
bool operator!=(std::nullptr_t, const nullable<T2>& rhs)
{
return rhs.m_hasValue;
}
}
#endif // COMMON_NULLABLE_H

Why is std::complex real member function not const?

Any reason for the member functions "real" and "imag" in the std::complex class not to be const?
There are two overloads for real in the complex class template:
T real() const;
void real(T);
The first on is const, so that can't be what you're asking about.
The second one, which takes a T argument and returns nothing, is not const, because it's a "setter" method—the whole point of it is to change the state of the object, so it had better not be const.
Let's look at the C++ Standard:
C++ 2011 Section 26.4.2 Class Template Complex
namespace std {
template<class T>
class complex {
public:
typedef T value_type;
complex(const T& re = T(), const T& im = T());
complex(const complex&);
template<class X> complex(const complex<X>&);
T real() const;
void real(T);
T imag() const;
void imag(T);
complex<T>& operator= (const T&);
complex<T>& operator+=(const T&);
complex<T>& operator-=(const T&);
complex<T>& operator*=(const T&);
complex<T>& operator/=(const T&);
complex& operator=(const complex&);
template<class X> complex<T>& operator= (const complex<X>&);
template<class X> complex<T>& operator+=(const complex<X>&);
template<class X> complex<T>& operator-=(const complex<X>&);
template<class X> complex<T>& operator*=(const complex<X>&);
template<class X> complex<T>& operator/=(const complex<X>&);
};
}
I'd say that it's pretty clearly stated that std::complex::real() and std::complex::imag() are const methods.

Relational Operator Implementation Dilemma

I'm in the process of designing several classes that need to support operators !=, >, <=, and >=. These operators will be implemented in terms of operators == and <.
At this stage, I need to make a choice between inheritance¹ and forcing my consumers to use std::rel_ops² "manually".
[1] Inheritance (possible implementation):
template<class T> class RelationalOperatorsImpl
{
protected:
RelationalOperatorsImpl() {}
~RelationalOperatorsImpl() {}
friend bool operator!=(const T& lhs, const T& rhs) {return !(lhs == rhs);}
friend bool operator>(const T& lhs, const T& rhs) {return (rhs < lhs);}
friend bool operator<=(const T& lhs, const T& rhs) {return !(rhs < lhs);}
friend bool operator>=(const T& lhs, const T& rhs) {return !(lhs < rhs);}
};
template<typename T> class Foo : RelationalOperatorsImpl< Foo<T> >
{
public:
explicit Foo(const T& value) : m_Value(value) {}
friend bool operator==(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value == rhs.m_Value);}
friend bool operator<(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value < rhs.m_Value);}
private:
T m_Value;
};
[2] std::rel_ops glue:
template<typename T> class Foo
{
public:
explicit Foo(const T& value) : m_Value(value) {}
friend bool operator==(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value == rhs.m_Value);}
friend bool operator<(const Foo& lhs, const Foo& rhs) {return (lhs.m_Value < rhs.m_Value);}
private:
T m_Value;
};
void Consumer()
{
using namespace std::rel_ops;
//Operators !=, >, >=, and <= will be instantiated for Foo<T> (in this case) on demand.
}
I'm basically trying to avoid code repetition. Any thoughts as to which method "feels" better?
Have you considered using boost, and having your class inherit from boost::less_than_comparable<T> and boost::equality_comparable<T>? It is akin to your first suggestion, with some pros and cons. Pros: avoids code duplication; Cons: creates a dependency on boost.
Since boost is a very common C++ library (if you don't use it already, you should seriously consider start using it), the con factor is dimmed.
I think std::rel_ops is quite nice, but there's one thing to consider first: std::rel_ops provides operators as template functions that accept two parameters of the same type. Because most conversions (including e.g. arithmetic promotions and user-defined conversions) are not performed when template argument deduction occurs, this means that you would not be able to use any of these additional operators (e.g. !=) with such conversions.
E.g. if you have a class MyInt that attempts to behave like a regular integer, you might have written conversion functions/constructors or templated operators so that you can do
MyInt x, y;
x < 5;
9 == x;
However,
x > 5;
30 <= x;
won't work (with std::rel_ops) because the two arguments are of different types, so template argument deduction will fail.