Created
April 21, 2015 23:33
-
-
Save santa4nt/b9e2aad53469e5b494da to your computer and use it in GitHub Desktop.
A sample usage of traits template technique to do type-agnostic comparison.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class C | |
{ | |
public: | |
C(const int i) : | |
_i(i) | |
{ | |
} | |
int Get() const | |
{ | |
return _i; | |
} | |
private: | |
const int _i; | |
}; | |
static inline bool operator== (const C& lhs, const C& rhs) | |
{ | |
return lhs.Get() == rhs.Get(); | |
} | |
template <typename cT> | |
struct class_traits { }; | |
template<> | |
struct class_traits<C> | |
{ | |
typedef C class_type; | |
static inline bool Eq (const class_type &lhs, const class_type &rhs) | |
{ | |
return lhs.Get() == rhs.Get(); | |
} | |
}; | |
template <typename cT> | |
class Container | |
{ | |
public: | |
typedef cT class_type; | |
typedef class_traits<class_type> traits_type; | |
Container(const class_type& rc) : | |
_rc(rc) | |
{ | |
} | |
bool Eq(const class_type& other) const | |
{ | |
traits_type::Eq(_rc, other); | |
} | |
private: | |
const class_type& _rc; | |
}; | |
typedef Container<C> CContainer; | |
int main() | |
{ | |
C c1(42); | |
C c2(42); | |
std::cout << std::boolalpha << "c1 == c2 ? " << (c1 == c2) << std::endl; | |
CContainer cc(c1); | |
std::cout << std::boolalpha << "cc.Eq(c2) ? " << cc.Eq(c2) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment