开发者

Is it possible to specialize template with pointer to function type that way it can see all the types used in this pointer separately?

#include <iostream>

template<typename T_function_type>
struct pointer_wrapper {

    T_function_type function_pointer;

    explicit pointer_wrapper(T_function_type ptr) : function_pointer(ptr) { }

    ~pointer_wrapper() { }

};

template<typename T_return, typename T_arg1, typename T_arg2>
pointer_wrapper<T_return (*)(T_arg1, T_arg2)> fabricate_some_trait(T_return (*ptr)(T_arg1, T_arg2)) {

    return pointer_wrapper<T_return (*)(T_arg1, T_arg2)>(ptr);

}

void hello(std::string const& name, std::string const& surname) {

    std::cout << "Hi " << name << " " << surname << "! ";

    std::cout << "Was wondering if it\'s possible to modify ";

    std::cout << "some_trait template in that way that it\'s ";

    std::cout << "capable of deducing function (as well as ";

    std::cout << "static and member one) type like the ";

    std::cout << "template function fabricate_some_trait is. ";

    std::cout << "So I can use these traits in typedef. ";

    std::cout << "Will be perfect if no <functional>, ";

    std::cout << "Boost.Function nor sigc::signal is going ";

    std::cout << "to be used. Hope you can help and sorry ";

    std::cout << "in advance about the form of this question, ";

    std::cout << "just feeling good today." << std::endl;

    std::cout << "Cheers!" << std::endl;

}

int main() {

    // need
    // some_trait<hello>::function_type hello_pointer = hello;
    // hello_pointer("Stackoverflow", "User");

    fabricate_some_trait(hello).function_pointer("Stackoverflow", "User");

}

/*
template<typename T_return_type(*)(typename T_arg, typename T_arg2)>
struct some_trait {

    typedef开发者_开发问答 T_return (*function_type)(T_arg1, T_arg2);

    typedef T_return result_type;

    typedef T_arg1 arg1_type;

//  (...)

};
*/


You want boost's type traits, specifically the function traits:

http://www.boost.org/doc/libs/1_43_0/libs/type_traits/doc/html/boost_typetraits/reference/function_traits.html

It works just fine with normal C function pointers, no need to use boost::function for sigc::signal's. With the function traits you can separately extract the return type and each of the parameter types, no need to do the specialization yourself.

If you can't use boost at all, you could still examine their implementation to get the general idea of how it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜