Template functors vs functions

荒凉一梦 提交于 2019-12-07 08:28:47

问题


I have been looking at some of the Boost source code and noticed they implement templated functions by using a functor instead of a plain function? Is there a reason for this?

For example:

template<typename Foo, typename Bar>
struct functor {
    Bar operator()(const Foo& foo) {
        return foo.as_bar();
    }
};

as opposed to:

template<typename Foo, typename Bar>
Bar func(const Foo& foo) {
    return foo.as_bar();
}

The only advantage I can come up with is it allows classes to inherit the function?


回答1:


There are two main reasons: The first is, as pythonic metaphor noted, partial specialization is only valid for classes and not functions. Note that functions can use overloads to overcome this problem generally, but often if you are doing metaprogramming it's easier and more generic to use partial specialization. I'd actually think this was the main reason.

The second reason is that anytime that code wants to accept a function object (like in the STL, e.g. std::transform), it will have a type template parameter. If you pass a functor or a lambda, the exact type is known at compile time, and you don't pay for indirection, and inlining can be performed. If you pass a function pointer (or a std::function), only the signature is known at compile time, and you pay for an indirection (and you can't inline). For instance, std::sort can be considerably faster with a functor than a function pointer.

Note that there is a little used feature called function pointer template parameters; these are non type template parameters that specialize on a specific function, and thus can remove indirection. However, if you use one of these, you can't use a functor at all. So most code that wants to accepts a function object does it the way I described above.



来源:https://stackoverflow.com/questions/31359041/template-functors-vs-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!