参见英文答案 Function template return type deduction5个 是否有可能找出函数的返回类型和参数类型并将它们用作模板类型?请考虑以下示例: template typename ret, typename inclass Bar { // Some code}int
是否有可能找出函数的返回类型和参数类型并将它们用作模板类型?请考虑以下示例:
template <typename ret, typename in>
class Bar {
// Some code
}
int foo(float x) {
return 0;
}
int main() {
Bar<int, float> b; // Can this be done automatically by inspection of foo at compile time?
}
我可以使用foo的函数签名来设置Bar的模板类型吗?
是的先生.template <class Function>
struct BarFor_;
template <class Ret, class In>
struct BarFor_<Ret(*)(In)> {
using type = Bar<Ret, In>;
};
template <auto function>
using BarFor = typename BarFor_<decltype(function)>::type;
现在您可以通过以下方式获取类型:
BarFor<foo> b;
See it live on Coliru
