I have a templated function:
template <typename my_func> int foo(int x, int y) {
my_func bar;
return bar(x, y);
}
Run Code Online (Sandbox Code Playgroud)
which I can use with following functor:
struct _compare {
int operator()(int x, int y) { return x-y; }
};
Run Code Online (Sandbox Code Playgroud)
Usage: foo<_compare>(int x, int y)
In fact there is a tight loop in foo and thus i'm trying to pass pointer to functions that can be inlined at compile time.
Now I want to use a function from 3rd party lib, which is templated fuctor by itself. The new functor is like:
template<typename Scalar> struct _compare {
Scalar operator()(const Scalar& a, const Scalar& b) const {
return a-b;
}
};
Run Code Online (Sandbox Code Playgroud)
And I can't make it compile. I've tried foo<_compare<char>>(int x, int y)
I've tried
const char t = 0;
foo<_compare<t>>(int x, int y);
Run Code Online (Sandbox Code Playgroud)
I've tried to foo<_compare>(int x, int y) and change foo to
template <typename my_func> foo(int x, int y) {
my_func<char> bar;
bar(x, y);
}
Run Code Online (Sandbox Code Playgroud)
As I need only _compare < char > for sure.
Any hints?
My preferred solution would be to do like the STL does: always pass the function object as parameter:
template<typename my_func>
void foo(int x, int y, my_func bar) {
bar(x, y);
}
Run Code Online (Sandbox Code Playgroud)
Then, it doesn't matter if my_func is a templated class, a lambda, a non templated class or even a function pointer. It just work.
Usage:
foo(int x, int y, _compare{});
foo(int x, int y, _compare<char>{});
foo(int x, int y, [](int, int){ return false; });
Run Code Online (Sandbox Code Playgroud)
This Live example shows that C++ completely elide both callable, and the function call and its result.
Also, the GCC ABI has no storage for empty classes sent as parameter to a function, removing overhead if not inlined.
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |