Skip to content

Latest commit

 

History

History
915 lines (823 loc) · 27.6 KB

README.md

File metadata and controls

915 lines (823 loc) · 27.6 KB

The Art of C++ / Operators

Release TravisCI AppVeyor Coverage

The Art of C++ / Operators is a zero-dependency C++11 single-header library that provides highly efficient, move aware operators for arithmetic data types.

Table of Content

Preface
Rationale
Example
Requirements
Installation
Provided Templates
Commutativity
RValue References
noexcept
Changelog
License

Preface

The Art of C++ / Operators is the next logical step in the evolution of the Boost.Operators library, whose maintainer I became in 2002. Since then, C++ has changed significiantly and with C++11, the time has come for a complete rewrite and to get rid of some very old legacy code and work-arounds.

Rationale

Overloaded operators for class types typically occur in groups. If you can write x + y, you probably also want to be able to write x += y. If you can write x < y, you also want x > y, x >= y, and x <= y. Moreover, unless your class has really surprising behavior, some of these related operators can be defined in terms of others (e.g. x >= y!(x < y)).

Replicating these operators for multiple classes is both tedious and error-prone. The Art of C++ / Operators templates help by generating operators for you based on other operators you've defined in your class.

The generated operators are overloaded to take full advantage of move-aware types and are carefully written to allow the compiler to apply important optimizations to avoid unneccessary temporary objects. All generated operators are automatically marked noexcept when the underlying base operations are themself marked as noexcept.

Example

#include <tao/operators.hpp>

class MyInt
  : tao::operators::commutative_addable< MyInt >,
    tao::operators::multipliable< MyInt, double >
{
public:
  // create a new instance of MyInt
  MyInt( const int v ) noexcept;

  // copy and move constructor
  MyInt( const MyInt& v ) noexcept;
  MyInt( MyInt&& v ) noexcept; // optional

  // copy and move assignment
  MyInt& operator=( const MyInt& v ) noexcept;
  MyInt& operator=( MyInt&& v ) noexcept; // optional

  // addition of another MyInt
  MyInt& operator+=( const MyInt& v ) noexcept;
  MyInt& operator+=( MyInt&& v ) noexcept; // optional

  // multiplication by a scalar
  MyInt& operator*=( const double v ) noexcept;
};

then the library's templates generate the following operators:

// generated by tao::operators::commutative_addable< MyInt >
MyInt   operator+( const MyInt& lhs, const MyInt& rhs ) noexcept;
MyInt&& operator+( const MyInt& lhs, MyInt&&      rhs ) noexcept;
MyInt&& operator+( MyInt&&      lhs, const MyInt& rhs ) noexcept;
MyInt&& operator+( MyInt&&      lhs, MyInt&&      rhs ) noexcept;

// generated by tao::operators::multipliable< MyInt, double >
MyInt   operator*( const MyInt& lhs, const double& rhs ) noexcept;
MyInt   operator*( const MyInt& lhs, double&&      rhs ) noexcept;
MyInt&& operator*( MyInt&&      lhs, const double& rhs ) noexcept;
MyInt&& operator*( MyInt&&      lhs, double&&      rhs ) noexcept;

Note: The // optional in class MyInt above marks methods that you typically only add when your class benefits from an rvalue reference parameter. If there is no benefit for the implementation, you can just omit these methods. If you leave them out, The Art of C++ / Operators will simply call the corresponding non-movable version that takes the parameter by const lvalue reference.

Requirements

Requires C++11 or newer. Tested with:

  • GCC 4.7+
  • Clang 3.2+
  • Visual Studio 2015+

Remember to enable C++11, e.g., provide -std=c++11 or similar options.

Note: If you use or test the library with other compilers/versions, e.g., Visual C++, Intel C++, or any other compiler we'd like to hear from you.

Note: For compilers that don't support noexcept, see chapter noexcept.

Installation

The Art of C++ / Operators is a single-header library. There is nothing to build or install, just copy the header somewhere and include it in your code.

Provided Templates

The following table gives an overview of the available templates. Note that the "Provides" and "Requires" columns are just a basic overview. Multiple overloads per provided operator might exist to ensure the most efficient implementation for each case, exploiting move-semantics when possible and (unless explicitly disabled) pass-through of temporary values to avoid creating new temporaries.

Each overload of an operator is marked noexcept when the required operation(s) that are used to implement it are also marked noexcept.

TemplateProvidesRequires
equality_comparable< T > T != T T == T
equality_comparable< T, U > T != U
U == T
U != T
T == U
less_than_comparable< T > T > T
T <= T
T >= T
T < T
less_than_comparable< T, U > T <= U
T >= U
U < T
U > T
U <= T
U >= T
T < U
T > U
equivalent< T > T == T T < T
equivalent< T, U > T == U T < U
T > U
partially_ordered< T > T > T
T <= T
T >= T
T < T
T == T
partially_ordered< T, U > T <= U
T >= U
U < T
U > T
U <= T
U >= T
T < U
T > U
T == U
commutative_addable< T > T + T T += T
commutative_addable< T, U > T + U
U + T
T += U
addable< T > T + T T += T
addable< T, U > T + U T += U
addable_left< T, U > U + T T( U )
T += T
subtractable< T > T - T T -= T
subtractable< T, U > T - U T -= U
subtractable_left< T, U > U - T T( U )
T -= T
commutative_multipliable< T > T * T T *= T
commutative_multipliable< T, U > T * U
U * T
T *= U
multipliable< T > T * T T *= T
multipliable< T, U > T * U T *= U
multipliable_left< T, U > U * T T( U )
T *= T
dividable< T > T / T T /= T
dividable< T, U > T / U T /= U
dividable_left< T, U > U / T T( U )
T /= T
modable< T > T % T T %= T
modable< T, U > T % U T %= U
modable_left< T, U > U % T T( U )
T %= T
commutative_andable< T > T & T T &= T
commutative_andable< T, U > T & U
U & T
T &= U
andable< T > T & T T &= T
andable< T, U > T & U T &= U
andable_left< T, U > U & T T( U )
T &= T
commutative_orable< T > T | T T |= T
commutative_orable< T, U > T | U
U | T
T |= U
orable< T > T | T T |= T
orable< T, U > T | U T |= U
orable_left< T, U > U | T T( U )
T |= T
commutative_xorable< T > T ^ T T ^= T
commutative_xorable< T, U > T ^ U
U ^ T
T ^= U
xorable< T > T ^ T T ^= T
xorable< T, U > T ^ U T ^= U
xorable_left< T, U > U ^ T T( U )
T ^= T
left_shiftable< T > T << T T <<= T
left_shiftable< T, U > T << U T <<= U
right_shiftable< T > T >> T T >>= T
right_shiftable< T, U > T >> U T >>= U
incrementable< T > T++ ++T
decrementable< T > T-- --T

The following templates provide common groups of related operations. For example, since a type which is left shiftable is usually also right shiftable, the shiftable template provides the combined operators of both.

TemplateProvides
totally_ordered< T > equality_comparable< T >
less_than_comparable< T >
totally_ordered< T, U > equality_comparable< T, U >
less_than_comparable< T, U >
commutative_ring< T > commutative_addable< T >
subtractable< T >
commutative_multipliable< T >
commutative_ring< T, U > commutative_addable< T, U >
subtractable< T, U >
subtractable_left< T, U >
commutative_multipliable< T, U >
ring< T > commutative_addable< T >
subtractable< T >
multipliable< T >
ring< T, U > commutative_addable< T, U >
subtractable< T, U >
subtractable_left< T, U >
multipliable< T, U >
field< T > commutative_ring< T >
dividable< T >
field< T, U > commutative_ring< T, U >
dividable< T, U >
dividable_left< T, U >
ordered_commutative_ring< T > commutative_ring< T >
totally_ordered< T >
ordered_commutative_ring< T, U > commutative_ring< T, U >
totally_ordered< T, U >
ordered_ring< T > ring< T >
totally_ordered< T >
ordered_ring< T, U > ring< T, U >
totally_ordered< T, U >
ordered_field< T > field< T >
totally_ordered< T >
ordered_field< T, U > field< T, U >
totally_ordered< T, U >
commutative_bitwise< T > commutative_andable< T >
commutative_orable< T >
commutative_xorable< T >
commutative_bitwise< T, U > commutative_andable< T, U >
commutative_orable< T, U >
commutative_xorable< T, U >
bitwise< T > andable< T >
orable< T >
xorable< T >
bitwise< T, U > andable< T, U >
orable< T, U >
xorable< T, U >
bitwise_left< T, U > andable_left< T, U >
orable_left< T, U >
xorable_left< T, U >
shiftable< T > left_shiftable< T >
right_shiftable< T >
shiftable< T, U > left_shiftable< T, U >
right_shiftable< T, U >
unit_steppable< T > incrementable< T >
decrementable< T >

Commutativity

For some templates, there are both commutative and non-commutative versions available. If the class you are writing is commutative wrt an operation, you should prefer the commutative template, i.e., the one which has commutative_ at the beginning.

It will be more efficient in some cases because it can avoid to create an extra temporary for the result and it has fewer requirements.

The one-argument version of the commutative template provides the same operators as the non-commutative one, but you can see from the result type in which cases creating a temporary (returning T) can be avoided (returning T&&).

For the two-argument version, commutative_{OP}< T, U > provides the operators of both {OP}< T, U > and {OP}_left< T, U >, again the return type indicates those cases where an extra temporary is avoided.

RValue References

As you can see above, several overloads of some operators return rvalue references. This helps to eliminate temporaries in more complicated expressions, but some people consider it dangerous. The argument against returning rvalue references usually is something like:

const auto& result = a + b + c;

where they expect a temporary to be returned from the expression a + b + c, and the lifetime of the temporary can be extended by binding it to a reference.

While this would work if an actual temporary value is returned, it does not work with the second operator + returning an rvalue reference to the intermediate temporary created by the first operator +.

I consider the above code bad style that has no place in modern C++. It should be replaced by

const auto result = a + b + c;

and the problem goes away. Also, if you expect an expression to return a temporary value, but you don't verify your assumption, it is your fault for basing your code on those assumptions.

There is, however, one problem where the above binding to a references happens behind the scenes, i.e. without being immediately visible. It may happen if you are using a range-based for-loop. The problem in this case is not limited to returning rvalue references, hence you should always make sure that you do not mix any kind of expression other than directly naming a variable when using a range-based for-loop. Example:

// instead of this:
for( const auto& e : a + b + c ) { ... }

// always use something like this:
const auto r = a + b + c;
for( const auto& e : r ) { ... }

With all that said, you can disable returning rvalue references by defining TAO_OPERATORS_NO_RVALUE_REFERENCE_RESULTS. If it is set, all operators will return a value (an rvalue) instead of rvalue references.

noexcept

If your compiler does not support noexcept, the following might be a viable work-around:

#include <utility> // make sure it's included before the following!
#define noexcept(...)
#include <tao/operators.hpp>
#undef noexcept

With this little hack, The Art of C++ / Operators can be used with GCC 4.4+.

Changelog

1.0.0

Released 2018-02-13

  • Initial release.

License

The Art of C++ is certified Open Source software. It may be used for any purpose, including commercial purposes, at absolutely no cost. It is distributed under the terms of the MIT license reproduced here.

Copyright (c) 2013-2018 Daniel Frey

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.