开发者

Variadic templates question

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
functiona开发者_高级运维l.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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜