加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 模板模板函数参数

发布时间:2020-12-16 04:57:06 所属栏目:百科 来源:网络整理
导读:参见英文答案 How to pass a template function in a template argument list2个 对于我的生活,我无法让这个简单的奥术模板魔法工作: templatetypename T,int a,int bint f(T v){ return v*a-b; // just do something for example}templatetypename T,int b
参见英文答案 > 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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读