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

Using template types with arguments initialized

本文关键字:类型 参数 初始化      更新时间:2023-10-16

如何使用模板类来调用带有一些默认参数的构造函数?这可能吗?

前任:

#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;
}

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

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


我想做到这一点的方法是封装。 谢谢 @jive-达森

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"

我不确定你在问什么,但也许下面的模板就是你想要的。请注意,模板参数位于尖括号<>,而不是括号中。

#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"
}

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

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

这一行没有意义,因为HoHoHo需要一个类型模板参数:

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

我想你的意思是:

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