Partialization of a partial template template with a member function pointer

I have the following working code:

class person { private: int age_; public: person() : age_(56) {} void age(int a) { age_ = i; } } template < class T, void (T::* ...FUNC)(int) > class holder; template < class T, void (T::*FUNC)(int)> class holder<T, FUNC> { public: typedef typename T::value_type value_type; public: explicit holder() : setter(FUNC) { std::cout << "func\n"; } private: std::function<void (value_type&, int)> setter; }; template < class T> class holder<T> { public: explicit holder() { std::cout << "plain\n"; } }; int main() { holder<person> h1; holder<person, &person::age> h2; // this does not work: holder<int> h3; } 

I know that in the case of int (or any other type of non-class, structure or union) the code does not work due to the expect member function in the second argument of the template.

My question is how to change the code to make it work. I need it to work in a way that makes it easier to use my owner class.

I tried it with a feature type, and also moved the pointer to a member function in the class constructor. Without success.

Any suggestions? Thanks in advance!

+4
source share
1 answer

Update: I got it to work with std::conditional :

 template < class T, void (std::conditional<std::is_class<T>::value, T, struct dummy>::type::* ...FUNC)(int) > class holder; 

Another possible solution is to use a subclass:

 template < class T, void (T::*FUNC)(int) > class class_holder { public: typedef typename T::value_type value_type; public: explicit class_holder() : setter(FUNC) { std::cout << "func\n"; } protected: std::function<void (value_type&, int)> setter; } template <class T, bool IsClass = std::is_class<T>::value> class holder; template <class T> class holder<T, true> : public class_holder<T> { public: template <void (T::*FUNC)(int) > class with_member : public class_holder<T, FUNC> { }; }; template <class T> class holder<T, false> { public: explicit holder() { std::cout << "plain\n"; } }; int main() { holder<person> h1; holder<person>::with_member<&person::age> h2; holder<int> h3; } 

I did not compile this, so tell me if something is not working.

+3
source

All Articles