基本的には、任意のCallable(関数型/ lambda/Functor)を取り、ラムダを返す関数テンプレートを作成します。 -taking-類似引数リストとあなたがgetLambdaFromCallable
に変更することができ、元の戻り値の型C++テンプレートのCallableの型(引数リストと戻り値)を推論する方法
#include <iostream>
int func(int a,float b) {
return a+b;
}
struct callable {
int operator() (int a, float b) {
return a+b;
}
};
template <typename RV, typename... Args>
auto getLambdaFromCallable(RV(&func)(Args...)) {
auto l = [&](Args... args) -> RV {
return func(args...);
};
return l;
}
int main() {
auto f = getLambdaFromCallable(func);
std::cout << f(1,2.f);
std::cout << " " << typeid(f).name();
auto f2 = getLambdaFromCallable(callable{}); // doesn't work
callable{}(1,2); // works
auto lambdaTest = [](int a, float b) -> int {
return a+b;
};
auto f3 = getLambdaFromCallable(lambdaTest);
}
' - > decltype(auto)'(参照を扱うための)ラムダの戻り値の型です。 – Jarod42
でも ' - > decltype(func(std :: forward(args)...))'なので、SFINAEフレンドリーです。 –
Jarod42
@ Jarod42ありがとうございました。 – Drax