c – 模板模板函数参数

前端之家收集整理的这篇文章主要介绍了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;
}

这可能不涉及仿函数吗?

解决方法

@H_301_10@ 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();
}
原文链接:https://www.f2er.com/c/120221.html

猜你在找的C&C++相关文章