C++ 将函数作为模板类型传递,并在c++; double f(const int&i){return 1.5*i;} 模板< typename\u out, 键入名称_in, _输出(*\uuu f)(常数输入&)> 类X{};//模板类X{}; int main() { xx;//X; }
如何简化此代码? 我想写注释中的代码。 C++11 result_of and decltype似乎有帮助,但我不够聪明,无法编写正确的代码来推断类中函数f的输入和输出类型。 你能帮我看看灯吗?C++ 将函数作为模板类型传递,并在c++; double f(const int&i){return 1.5*i;} 模板< typename\u out, 键入名称_in, _输出(*\uuu f)(常数输入&)> 类X{};//模板类X{}; int main() { xx;//X; },c++,templates,c++11,return-type-deduction,template-argument-deduction,C++,Templates,C++11,Return Type Deduction,Template Argument Deduction,如何简化此代码? 我想写注释中的代码。 C++11 result_of and decltype似乎有帮助,但我不够聪明,无法编写正确的代码来推断类中函数f的输入和输出类型。 你能帮我看看灯吗? 谢谢只需删除_out和_in参数并将参数更改为std::function: double f(const int& i) { return 1.5 * i; } template< typename _out, typename _in, _out (*__
谢谢只需删除_out和_in参数并将参数更改为std::function:
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;
}
#包括
#包括
双f(常数整数和整数){std::您是否正在使用a。抱歉…只是了解可能a是您正在寻找的?您的代码非常完美,但我忘记了类X的一个限制。它必须有一个空的默认构造函数,以便函数f不能以这种方式传递。目前为止的最佳解决方案…如果您不必为每个函数都编写包装器类,那就太好了:)
#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;
}