Wrap a function pointer in C++ with variadic template

后端 未结 3 1877
借酒劲吻你
借酒劲吻你 2020-12-15 07:58

The Question

I have a number of C++ functions void f(), R g(T a), S h(U a, V b) and so on. I want to write a template functi

相关标签:
3条回答
  • 2020-12-15 08:27

    There's a duplicate somewhere here, I remember it, but I can't find it... The conclusion of which being that it was impossible to pass the pointer's type and its value at the same time.

    Some hope lies in a suggestion for implicit type template parameters, which you can find here.

    0 讨论(0)
  • 2020-12-15 08:28

    This is the best I've been able to do so far:

    template<typename R, typename...A>
    struct S<R(A...)>
    {
        typedef R(*F)(A...);
        F f;
        constexpr S(F _f) : f(_f) { }
        inline R operator()(A... a)
        { return f(a...); }
    };
    
    #define wrapper(FUNC, ARGS...) (S<decltype(FUNC)>(FUNC))(ARGS)
    
    int f(float g);
    
    int main(void)
    {
        return wrapper(f, 3.0f);
    }
    

    Sadly I can't make it compile under MSVC.

    0 讨论(0)
  • 2020-12-15 08:29
    template<typename Fn, Fn fn, typename... Args>
    typename std::result_of<Fn(Args...)>::type
    wrapper(Args&&... args) {
        return fn(std::forward<Args>(args)...);
    }
    #define WRAPPER(FUNC) wrapper<decltype(&FUNC), &FUNC>
    

    //Usage:

    int min(int a, int b){
        return (a<b)?a:b;
    }
    
    #include<iostream>
    #include<cstdlib>
    int main(){
        std::cout<<WRAPPER(min)(10, 20)<<'\n';
        std::cout<<WRAPPER(rand)()<<'\n';
    }
    

    Alternatively, to get maybe quite less readable, but shorter syntax:

    #define WRAPPER(FUNC, ...) wrapper<decltype(&FUNC), &FUNC>(__VA_ARGS__)
    

    //Usage:

    int main(){
        sdt::cout<<WRAPPER(min, 10, 20)<<'\n';
        std::cout<<WRAPPER(rand)<<'\n';
    }
    
    0 讨论(0)
提交回复
热议问题