typedef does _not_ creates new type,
but sometimes, we really want _the_ same type but
with different _type_. Ok, it's a bit wordy.
Let's put it this way, define function signatures:
These will violate the One Definition Rule(ODR).
We can declare a function many times(asking to import function symbol during the linking stage), but only one definition is allowed.
What if, we really need to take the same type but with different _type_?
This is really useful for compile time checking and , well,
database query programming. (i.e get/set different properties but actually with same type underneath)
e.g:
stacked-crooked on-line code
but sometimes, we really want _the_ same type but
with different _type_. Ok, it's a bit wordy.
Let's put it this way, define function signatures:
typedef float ft_t; void float_me(float){}; void float_me(ft_t){};
These will violate the One Definition Rule(ODR).
We can declare a function many times(asking to import function symbol during the linking stage), but only one definition is allowed.
What if, we really need to take the same type but with different _type_?
This is really useful for compile time checking and , well,
database query programming. (i.e get/set different properties but actually with same type underneath)
e.g:
#include <string> #include <memory> #include <boost/serialization/strong_typedef.hpp> //Won't introduce new type; only type alias. typedef std::string FirstName_t; typedef std::string SecondName_t; struct Panda { FirstName_t FirstName; SecondName_t SecondName; }; template<typename T> struct firstname_alloc : std::allocator<T> { }; template<typename T> struct secondname_alloc : std::allocator<T> { }; struct Panda_Adv_1 { std::basic_string<char, std::char_traits<char>, firstname_alloc<char> > FirstName; std::basic_string<char, std::char_traits<char>, secondname_alloc<char> > SecondName; }; BOOST_STRONG_TYPEDEF(std::string, FirstName_bt) BOOST_STRONG_TYPEDEF(std::string, SecondName_bt) struct Panda_Adv_2 { FirstName_bt FirstName; SecondName_bt SecondName; }; int main(){ Panda p1 = {"Yuan_Zai", "Ha"}; //This compiles since both are std::string type; p1.FirstName = p1.SecondName; /* Won't Compile due to no implicit type conversion between * std::basic_string<char, std::char_traits<char>, firstname_alloc<char> > * std::basic_string<char, std::char_traits<char>, secondname_alloc<char> > Panda_Adv_1 p2 = {"Yuan_Zai", "Ha"}; p2.FirstName = p2.SecondName; */ /* Won't compile due to the same reason, but using * Boost's strong_typedef Panda_Adv_2 p3 = {"Yuan_Zai", "Ha"}; p3.FirstName = p3.SecondName; */ }
stacked-crooked on-line code
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.