c – 模板模板函数参数

参见英文答案 > How to pass a template function in a template argument list2个
对于我的生活,我无法让这个简单的奥术模板魔法工作:
template<typename T,int a,int b>
int f(T v){
  return v*a-b; // just do something for example
}

template<typename T,int b,template<typename,int,int> class func>
class C{
  int f(){
    return func<T,a,b>(3);
  }
};

int main(){
  C<float,3,2,f> c;
}

这可能不涉及仿函数吗?

解决方法

f应该是一个类 – 你有一个功能.

见下文:

// Class acts like a function - also kNown as functor.
template<typename T,int b>
class f
{
  int operator()(T v)
  {
    return v*a-b; // just do something for example
  }
};

template<typename T,int> class func>
class C
{
  int f()
  {
    return func<T,b>(3);
  }
};

int main()
{
  C<float,f> c;
}

…如果需要移植遗留代码,请使用改编版本(将函数调整为类模板):

#include <iostream>


template<typename T,int b>
int f(T v)
{
  std::cout << "Called" << std::endl;
  return v*a-b; // just do something for example
}

template<typename T,int> class func>
struct C
{
  int f()
  {
    return func<T,b>(3);
  }
};

template <class T,int b>
struct FuncAdapt
{
  T x_;
  template <class U>
  FuncAdapt( U x )
  : x_( x )
  {}
  operator int() const
  {
    return f<T,b>( x_ );
  }
};

int main()
{
  C<float,FuncAdapt > c;
  c.f();
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...