函数模板和类模板有什么区别?

时间:2010-09-18 09:04:23

标签: c++ templates

我对C ++函数模板和类模板提供的奇怪语法感到困惑。快速浏览下面的代码:

#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>
#include <vector>
using namespace std;

template <class op1,class op2>
class compose_fg_x_t : public unary_function<typename op2::argument_type,typename op1::result_type>{
public:
// constructor

compose_fg_x_t(const op1& arg1,const op2& arg2): p1(arg1),p2(arg2){
}
//function call
typename op1::result_type operator()(const typename op2::argument_type& x) const{
    return p1(p2(x));
  }

private:
op1 p1;
op2 p2;

};

template <class Op1,class Op2>
inline compose_fg_x_t<Op1,Op2> compose_fg_x(const Op1& p1,const Op2& p2){
    return compose_fg_x_t<Op1,Op2>(p1,p2);
}
int main(int argc, char *argv[])
{
int a[] = {1,2,3,4,5};
vector<int> IntVec(a,a+sizeof(a)/sizeof(int));
copy(IntVec.begin(),IntVec.end(),ostream_iterator<int>(cout," "));
cout<<endl;
transform(IntVec.begin(),IntVec.end(),ostream_iterator<int>(cout,"    "),compose_fg_x( bind2nd(multiplies<int>(),5),bind2nd(plus<int>(),10) ));
transform(IntVec.begin(),IntVec.end(),ostream_iterator<int>(cout," "),compose_fg_x_t(   bind2nd(multiplies<int>(),5),bind2nd(plus<int>(),10) ));
return 0;
}

所以,我的问题是,为什么第一个转换是正确的而第二个转换不正确?辅助函数compose_fg_x的作用是返回基础compose_fg_x_t类型的对象。我试图省略间接函数调用,它无法编译。为什么呢?

1 个答案:

答案 0 :(得分:4)

模板参数只能用于函数模板,而不能用于类模板。帮助函数的整个要点,例如make_pair(或您的compose_fg_x)是为了规避这一限制。

这是一个稍微不那么复杂的例子来说明问题:

#include <utility>

int main()
{
    auto x = std::make_pair(3, 4);   // function template arguments are deduced
    auto y = std::pair(3, 4);        // error: missing class template arguments
}