Created
August 30, 2020 04:04
-
-
Save arthurmco/92afb6c8628cbd5ef0611deea9770da1 to your computer and use it in GitHub Desktop.
c++ traits, more or less
This file contains 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 <string> | |
#include <sstream> | |
/// sort-of trait system using template specialization | |
/// | |
/// It is better than inheritance. | |
/// Avoid the object to inherit from a lot of places. | |
/// Instead, you can create a trait, and the user "implement" that. | |
/// | |
/// read https://accu.org/index.php/journals/442 for more insights | |
template <typename T> | |
class Trait { | |
private: | |
T impl_; | |
public: | |
Trait(T impl) : impl_(impl) {} | |
[[noreturn]] | |
std::string getName() { static_assert("this should not be called, use the derived ones"); } | |
}; | |
template <> | |
class Trait<int> { | |
private: | |
int impl_; | |
public: | |
Trait(int impl) : impl_(impl) {} | |
std::string getName() { return "integer"; } | |
}; | |
template <> | |
class Trait<char> { | |
private: | |
char impl_; | |
public: | |
Trait(char impl) : impl_(impl) {} | |
std::string getName() { | |
std::stringstream ss; | |
ss << "char ("; | |
ss << impl_; | |
ss << ")"; | |
return ss.str(); | |
} | |
}; | |
int main() { | |
Trait<int> ti{1}; | |
Trait<char> tc{'A'}; | |
Trait<bool> tb{true}; | |
printf("%s\n", ti.getName().c_str()); | |
printf("%s\n", tc.getName().c_str()); | |
printf("%s\n", tb.getName().c_str()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment