最近、私はいくつかのコードの繰り返しを解決するためにテンプレート関数を書きました。次のようになります。
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) {
}
};
なぜそうなのか(なぜそれが型を推定できないのか)と(もし可能であれば)このコードを参照で動作させるにはどうすればよいですか? 実例
@ user3365922が試してみました。解決策のように感じますが、機能しません
—
bartop
Args&&...
そしてstd::forward
?