최근에 코드 반복을 해결하기 위해 템플릿 함수를 작성했습니다. 다음과 같이 보입니다 :
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?