【发布时间】:2019-10-23 10:37:57
【问题描述】:
最近我写了一个模板函数来解决一些代码重复。它看起来像这样:
template<class T, class R, class... Args>
R call_or_throw(const std::weak_ptr<T>& ptr, const std::string& error, R (T::*fun)(Args...), Args... args) {
if (auto sp = ptr.lock())
{
return std::invoke(fun, *sp, args...);
}
else
{
throw std::runtime_error(error.c_str());
}
}
int main() {
auto a = std::make_shared<A>();
call_or_throw(std::weak_ptr<A>(a), "err", &A::foo, 1);
}
这段代码非常适合class A,看起来像这样:
class A {
public:
void foo(int x) {
}
};
但无法编译为这样的:
class A {
public:
void foo(const int& x) {
}
};
为什么会这样(我的意思是为什么它无法推断出类型)以及如何(如果可能的话)使这段代码与引用一起工作? Live example
【问题讨论】: