c++ - How to make policy dictate a member variable type? -
while trying apply policy-based design, got stuck on 1 (simplified):
template <class tprintpolicy, typename t> struct : private tprintpolicy { using tprintpolicy::print; t t; void foo() { print(t); } }; struct intpolicy { void print(int n) { std::cout << n << std::endl; } }; int main(int argc, char* argv[]) { a<intpolicy, int> a; a.foo(); return 0; }
and here's question: how should redefine class possible provide policy parameter template, let infer t on own, this:
a<intpolicy> a;
preferrably, policy definition should not more complicated now. ideas?
edit:
forgot mention not want policy export typedef. of course easy solution, cannot infer type of t on own?
make typedef within each policy gives policy's data type.
template <class tprintpolicy> struct : private tprintpolicy { using tprintpolicy::print; typename tprintpolicy::data_type t; void foo() { print(t); } }; struct intpolicy { typedef int data_type; void print(int n) { std::cout << n << std::endl; } }; int main(int argc, char* argv[]) { a<intpolicy> a; a.foo(); return 0; }
edit: personally, use typedef, though adds duplication, because believe makes code clearer. however, if want avoid it, try similar this.
#include <boost/typeof/typeof.hpp> template<typename t, typename class> t deduceargumenttype(void (class::*ptr)(t)) {} template <class tprintpolicy> struct : private tprintpolicy { using tprintpolicy::print; typedef boost_typeof(deduceargumenttype(&tprintpolicy::print)) data_type; data_type t; void foo() { print(t); } }; struct intpolicy { void print(int n) { std::cout << n << std::endl; } }; int main(int argc, char* argv[]) { a<intpolicy> a; a.foo(); return 0; }
it might possible boost.typetraits this, i'm not sure how.
Comments
Post a Comment