Template function as a template argument

后端 未结 4 425
庸人自扰
庸人自扰 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:50

    With generic lambda from C++14 you might do:

    template void a(T t) { /* do something */}
    template void b(T t) { /* something else */ }
    
    template 
    void function(F&& f) {
        f(someobj);
        f(someotherobj);
    }
    
    void test() {
        // For simple cases, auto&& is even probably auto or const auto&
        function([](auto&& t){ a(t); });
        function([](auto&& t){ b(t); });
    
        // For perfect forwarding
        function([](auto&& t){ a(std::forward(t)); });
        function([](auto&& t){ b(std::forward(t)); });
    }
    

    Can compilers still inline the calls if they are made via function pointers?

    They can, but it is indeed more complicated, and they may fail more often than with functor or template.

提交回复
热议问题