函数作为模板参数的多态签名(使用lambdas)
Polymorphic signature of function as template argument (using lambdas)
我努力了几个小时,还是没能把它修好。
我有一个模板化的类自旋锁:
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_of
在fun(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)...)
无效时,第二个重载将不参与重载解析。
相关文章:
- 为什么在C++20中对lambdas使用"std::bind_front"
- 使用lambdas初始化多维数组
- 我可以使用匿名lambdas坚持静态值
- C ;使用lambdas在类中有条件地扩展功能(MWE的SEG故障)
- C 使用多个lambdas/绑定以引用相同的功能
- 将lambdas/functions存储在std::vector中,而不使用std::function
- lambdas不使用功能接受std ::功能
- C功能指针使用C 11 lambdas
- 使用C 11中的lambdas值
- 在内存使用方面,templates+functors/lambdas是否次优
- 使用auto参数从lambdas返回值
- 如何使用QT5中的lambdas将具有int参数的信号连接到具有枚举参数with的插槽
- Qt连接函数-使用lambdas消除信号歧义
- 如何将async与不返回任何内容的lambdas一起使用
- 在c++中使用lambdas时出现奇怪的编译器消息
- 在绑定函数/使用lambdas测试消息传递代码时遇到麻烦
- C++使用lambdas对函数模板进行类型擦除
- 使用lambdas简化容器迭代
- 在模板类中使用lambdas
- 函数作为模板参数的多态签名(使用lambdas)