I'm trying to write a generic code for comparing std::functions using its target() template method. Here is my non-generic sample code:
#include <cstdio>
#include <functional>
static void bar() {}
static void baz() {}
bool cmp(std::function<void()> f1, std::function<void()> f2)
{
void (**t1)() = f1.target<void(*)()>();
void (**t2)() = f2.target<void(*)()>();
return (!t1 && !t2) || (t1 && t2 && *t1 == *t2);
}
int main(int argc, char *argv[])
{
std::function<void()> f1(bar), f2(baz), f3(bar);
printf("equal: %d\n", cmp(f1, f3));
printf("non-equal: %d\n", cmp(f1, f2));
return 0;
}
This compiles and runs fine with gcc 4.6.1 -std=c++-x . However when I'm trying to compile the following generic cmp function the compiler fails with parse error codes:
#include <cstdio>
#include <functional>
static void bar() {}
static void baz() {}
template<typename Result, typename ... Args>
bool cmp(std::function<Result(Args...)> f1, std::function<Result(Args...)> f2)
{
Result (**t1)(Args...) = f1.target<Result(*)(Args...)>();
Result (**t2)(Args...) = f2.target<Result(*)(Args...)>();
return (!t1 && !t2) || (t1 && t2 && *t1 == *t2);
}
int main(int argc, char *argv[])
{
std::function<void()> f1(bar), f2(baz), f3(bar);
printf("equal: %d\n", cmp(f1, f3));
printf("non-equal: %d\n", cmp(f1, f2));
return 0;
}
Error codes are:
functional.cpp: In function ‘bool cmp(std::function<_Res(_ArgTypes ...)>, std::function<_Res(_ArgTypes ...)>)’:
functional.cpp:11:44: error: expected primary-expression before ‘(’ token
functional.cpp:11:46: error: expected primary-expression before ‘)’ token
functional.cpp:11:52: error: expected primary-expression before ‘...’ token
functional.cpp:11:58: error: expected primary-expression before ‘)’ token
functional.cpp:12:44: error: expected primary-expression before ‘(’ token
functional.cpp:12:46: error: expected primary-expression before ‘)’ token
functional.cpp:12:52: error: expected primary-expression before ‘...’ token
functional.cpp:12:58: error: expected primary-expression before ‘)’ token
Any hints?
This should possibly be
f1.template target<Result(*)(Args...)>()
^^^^^^^^
and similar for the next line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With