Template function as a template argument

后端 未结 4 420
庸人自扰
庸人自扰 2020-12-01 02:03

I\'ve just got confused how to implement something in a generic way in C++. It\'s a bit convoluted, so let me explain step by step.


Consider such code:

4条回答
  •  旧巷少年郎
    2020-12-01 02:46

    Here's a way. It may not be the best, but it works:

    template 
    void function() {
        param(123);
        param(456);
    }
    
    void test()
    {
        function< void(*)(int), a >(); // space at end necessary to compiler
        function< void(*)(int), b >(); // because the C++ grammar is ambiguous
    }
    

    Whether or not they'll be inlined depends on the compiler, but I would be rather surprised if they weren't.

    EDIT: Okay, I'm a little off today and missed the part where the parameters are of different types. My bad.

    There may be a tricky way to do this with templates, but this is the easiest way I could think of:

    #define function(x) do { x(obj1); x(obj2) } while(0)
    

    I know, I know, "macros are evil," blah blah blah. It works. If function needs to be more complicated than your example you may run into problems, but it is much easier than anything I've been able to come up with.

提交回复
热议问题