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

c – 我可以轻松地创建一个模板函数,它接受任意类型的任意容器并

发布时间:2020-12-16 10:52:56 所属栏目:百科 来源:网络整理
导读:我正试图让这样的东西起作用: // This method is wrong,won't work,need your helptemplate template typename T class U void foo(U u) { T blah = *u.begin();}int main(int,char**){ vectorint myVec(4,10); foovectorint (myVec); // This is how I wan
我正试图让这样的东西起作用:

// This method is wrong,won't work,need your help
template < template <typename T> class U >
void foo(U& u) 
{
  T& blah = *u.begin();
}

int main(int,char**)
{
  vector<int> myVec(4,10);
  foo<vector<int> >(myVec); // This is how I want to call it,even better if I can leave the parameters out and just do foo(myVec);
  return EXIT_SUCCESS;
}

真的我想要做的是避免以下因为它似乎多余:

template <typename T,typename U>
void foo(U& u)
{
T& blah = *u.begin(); 
}

int main(int,10);
  foo<int,std::vector<int> >(myVec); // first int in parameters is redundant cause I already provide int as arg to vector
  return EXIT_SUCCESS;
}

解决方法

你可以做 :

template < typename U>
void foo(U& u) 
{
  typename U::value_type blah = *u.begin();
}

(编辑:李大同)

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

    推荐文章
      热点阅读