Created
October 30, 2013 10:18
-
-
Save jchnkl/7230205 to your computer and use it in GitHub Desktop.
Variadic templates, type deduction and type recursion
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
| template<typename T> | |
| class Printer { | |
| public: | |
| void print(void) | |
| { | |
| std::cerr << "ts: "; | |
| for (auto & i : ts) { | |
| std::cerr << i << ", "; | |
| } | |
| std::cerr << std::endl; | |
| } | |
| void add(const T & t) { ts.push_back(t); } | |
| protected: | |
| std::vector<T> ts; | |
| }; | |
| template<typename ... BASE> | |
| class Class : public Printer<BASE> ... { | |
| public: | |
| template<typename T> | |
| void add(const T & t) | |
| { | |
| static_cast<Printer<T> *>(this)->add(t); | |
| } | |
| void print(void) | |
| { | |
| print<BASE ...>(); | |
| } | |
| template<typename A> | |
| void print(void) | |
| { | |
| static_cast<Printer<A> *>(this)->print(); | |
| } | |
| template<typename A, typename B, typename ... ARGS> | |
| void print(void) | |
| { | |
| print<A>(); | |
| print<B, ARGS ...>(); | |
| } | |
| }; | |
| int main(int argc, char ** argv) | |
| { | |
| Class<int, std::string, double> c; | |
| c.add(1); | |
| c.add(2); | |
| c.add(std::string("3")); | |
| c.add(std::string("4")); | |
| c.add(std::string("5")); | |
| c.add(6.0); | |
| c.add(7.0); | |
| c.add(8.0); | |
| c.add(9.0); | |
| c.print(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment