Skip to content

Instantly share code, notes, and snippets.

@kdungs
Created September 15, 2015 11:21
Show Gist options
  • Save kdungs/91185c4da721d5603cc5 to your computer and use it in GitHub Desktop.
Save kdungs/91185c4da721d5603cc5 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <boost/serialization/strong_typedef.hpp>
BOOST_STRONG_TYPEDEF(double, Time)
BOOST_STRONG_TYPEDEF(double, Distance)
BOOST_STRONG_TYPEDEF(double, Velocity)
Velocity calculateVelocity(Distance d, Time t) {
return Velocity{static_cast<double>(d) / static_cast<double>(t)};
}
int main() {
// auto v = calculateVelocity(10.0, 5.0); // What is this? What is 10? What is 5? -> Compiler Error!
auto v = calculateVelocity(Distance{10.0}, Time{5.0});
std::cout << static_cast<double>(v) << '\n';
}
@kdungs
Copy link
Author

kdungs commented Sep 15, 2015

The overhead of casting is (theoretically) only on library side. For the user, it is fully transparent. They only use code as written in main. What could be of use is a general overload for streaming operators or even calculations…

I could think of something like

#define STRONG_TYPEDEF_WITH_OSTREAM(T, ALIAS)             \
    BOOST_STRONG_TYPEDEF(T, ALIAS)                        \
    std::ostream& operator<<(std::ostream& os, ALIAS a) { \
      os << static_cast<T>(a);                            \
      return os;                                          \
    }

(not tested)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment