在c++中传递函数作为模板类型并推导其类型

passing a function as template type and deducting its types in c++

本文关键字:类型 c++ 传递函数      更新时间:2023-10-16
double f(const int& i) { return 1.5 * i;  }
template<
    typename _out, 
    typename _in, 
    _out (*__f)(const _in&)> 
class X {}; // template <... __f> class X {};
int main()
{
    X<double, int, f> x; // X<f> x;
}

如何简化这段代码?我想把代码写在注释中。c++ 11的result_of和decltype似乎有所帮助,但我不够聪明,无法编写正确的代码来推断类内部函数f的输入和输出类型。你能帮我看到光明吗?由于

只需删除_out和_in参数,并将参数更改为std::function:

#include <functional>
#include <iostream>
double f(const int &i) { std::cout << "Func F" << std::endl; return 1.5 * i; }
struct functor_of_f {
    double operator()(const int &i)
    { std::cout << "Func F" << std::endl; return 1.5 * i; }
};
template <typename T> class X {
public:
  X(T t) { std::cout << t(5) << std::endl; }
  X() { std::cout << T()(5) << std::endl; }
}; // template <... __f> class X {};
int main(int argc, char* argv[]) {
  typedef std::function<double(int)> f_func;
  X<f_func> x1(f);
  X<decltype(f)> x2(f);
  X<std::function<double(int)>> x3(f);
  X<functor_of_f> x4;
  return 0;
}

更新了代码,增加了一个函子版本,问题是需要在类中拥有函数而不是作为自由函数