函数作为模板参数的多态签名(使用lambdas)

Polymorphic signature of function as template argument (using lambdas)

本文关键字:使用 lambdas 多态 参数 函数      更新时间:2023-10-16

我努力了几个小时,还是没能把它修好。

我有一个模板化的类自旋锁:

template<typename T> class spinlock {
  // ...
  volatile T *shared_memory;
};

我想创建这样的东西:

  // inside spinlock class
  template<typename F, typename... Ars>
  std::result_of(F(Args...))
  exec(F fun, Args&&... args) {
    // locks the memory and then executes fun(args...)
  };

但我正试图使用多态函数,以便我可以这样做:

spinlock<int> spin;
int a = spin.exec([]() {
  return 10;
});
int b = spin.exec([](int x) {
  return x;
}, 10); // argument here, passed as x
// If the signature matches the given arguments to exec() plus
// the shared variable, call it
int c = spin.exec([](volatile int &shared) {
  return shared;
}); // no extra arguments, shared becomes the
    // variable inside the spinlock class, I need to make
    // a function call that matches this as well
// Same thing, matching the signature
int d = spin.exec([](volatile int &shared, int x) {
  return shared + x;
}, 10); // extra argument, passed as x... should match too
// Here, there would be an error
int d = spin.exec([](volatile int &shared, int x) {
  return shared + x;
}); // since no extra argument was given 

基本上,我试图使一个exec函数接受F(Args...)F(volatile T &, Args...)作为参数。

但是我无法自动检测类型。我怎么才能做到呢?

首先,这个签名不能编译:

// inside spinlock class
template<typename F, typename... Ars>
std::result_of(F(Args...))
exec(F fun, Args&&... args) {
  // locks the memory and then executes fun(args...)
};

返回类型必须是

typename std::result_of<F(Args...)>::type

如果你的编译器实现了N3436,那么当fun(args...)不是一个有效的表达式时,这个函数将不参与重载解析,但这在c++ 11中是不需要的,也没有被许多编译器实现。您需要实现自己的SFINAE检查,以防止result_offun(args...)无效时给出错误,或者重写result_of

template<typename F, typename... Args>
auto
exec(F fun, Args&&... args) -> decltype(fun(std::forward<Args>(args)...))
{
  // locks the memory and then executes fun(args...)
}

然后,您可以为需要传入额外参数的函数重载它:

template<typename F, typename... Args>
auto
exec(F fun, Args&&... args) -> decltype(fun(*this->shared_memory, std::forward<Args>(args)...))
{
  // locks the memory and then executes fun(*shared_memory, args...)
}

fun(std::forward<Args>(args)...)无效时,第一个过载将不参与过载解析。当fun(*this->shared_memory, std::forward<Args>(args)...)无效时,第二个重载将不参与重载解析。