我努力了几个小时,但没能成功。
我有一个模板类自旋锁:
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...)
作为参数的函数。
但我无法自动检测类型。我怎么能做到这一点?