使用初始化参数的模板类型

时间:2018-05-01 23:59:56

标签: c++ templates

如何使用模板类,我可以使用一些默认参数调用构造函数?这可能吗?

前:

#include <iostream>
#include <string>

using namespace std;

template <class T> class HoHoHo {
public:
    HoHoHo<T>(T yell);
    template <class TT> friend std::ostream& operator<<(std::ostream&, const HoHoHo<TT> &);
private:
    T yell;
};
template <class T> HoHoHo<T>::HoHoHo(T yell) {this->yell = yell;}
template <class T> std::ostream& operator<<(std::ostream &o, const HoHoHo<T> &val){ return o << "HoHoHo " << val.yell << "."; }

class Cls{
public:
    Cls(int a=0, int b=0);
    friend std::ostream& operator<<(std::ostream&, const Cls &);
private:
    int a;
    int b;
};
Cls::Cls(int a, int b){ this->a = a; this->b = b; }
std::ostream& operator<<(std::ostream &o,  const Cls &val) { return o << val.a << "," << val.b; }

int main()
{
  Cls cls(2,3);
  HoHoHo<Cls> hohoho(cls);
  cout << hohoho << endl; //This prints "HoHoHo 2,3"

  //DO NOT WORK
  HoHoHo<Cls(3,4)> hohoho_test(); // Want something like this?
  cout << hohoho_test << endl; // to print "HoHoHo 2,3"

  return 0;
}

在这里,我希望能够使用一些默认值来调用模板类的构造函数。我如何实现这样的目标?

我可以编写另一个类来封装,但希望有更聪明的解决方案。

我想这样做的方法是封装。 thx @ jive-dadson

template<int A, int B> class Cls_ext: public Cls {
public:
    Cls_ext<A,B>(){ this->a = A; this->b = B;}
};

  HoHoHo<Cls_ext<3,4> > hohoho_test; 
  cout << hohoho_test << endl; // prints "HoHoHo 3,4"

3 个答案:

答案 0 :(得分:3)

我不确定你在问什么,但也许下面的模板就是你想要的。请注意,模板参数使用斜括号&lt;&gt;而不是括号。

#include <iostream>
#include <vector>

template<int A, int B>
class Cls{
public:
    Cls(): a(A), b(B) { }
    void Print(){ std::cout << a << "," << b << std::endl; }
private:
    int a;
    int b;
};

int main()
{
  std::vector<Cls<3,2>> vec(5); //Something like this?
  vec[0].Print(); // Should print "3,2"
}

答案 1 :(得分:2)

std::vector有一个特殊的构造函数,用于重复N次元素:

std::vector<Cls> vec(5, Cls(3,2));

答案 2 :(得分:0)

这一行毫无意义,因为HoHoHo需要类型模板参数:

  HoHoHo<Cls(3,4)> hohoho_test();

我认为你的意思是:

  HoHoHo<Cls> hohoho_test(Cls(3,4));