C++ - is it possible to extract class and argument types from a member function type in a template?

前端 未结 4 1689
孤独总比滥情好
孤独总比滥情好 2021-02-15 18:19

I would like to wrap member functions that conform to the type \'void (ClassType::Function)(ArgType)\' with a templated class. Later, I want to pass an instance of ClassType to

4条回答
  •  死守一世寂寞
    2021-02-15 18:39

    This is a poor re-implementation of ::std::mem_fn + ::std::bind, which are C++11 constructs. Here is how you might do this using those:

    #include 
    
    int main() {
       Foo foo;
       auto wrapper = ::std::bind(::std::mem_fn(&Foo::set), ::std::ref(foo), _1);
       wrapper(5); // Calls foo.set(5)
    }
    

    But, of course, you want a C++03 solution. Using Boost can get you this in C++03. I also believe that something like this is possible in C++03 with TR1. You can tell if you have that by seeing if #include  works. If you have TR1 those show up in the ::std::tr1 namespace.

    Now, there is one way in which it isn't. You've made the function pointer itself part of the type signature of the class. That's sort of an odd thing to do, but certainly possible as you already know. Being able to determine the ClassType and ArgType values at compile time is tricky though. You can do it with template function argument matching, but not usefully because C++03 doesn't have auto.

提交回复
热议问题