使用初始化参数的模板类型
Using template types with arguments initialized
如何使用模板类来调用带有一些默认参数的构造函数?这可能吗?
前任:
#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));
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- c++非类型参数包扩展
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 在不同的模板参数包之间分发非类型参数包
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 错误:一元"*"的类型参数无效(具有"int"):使用 mergesort 计算
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 作为模板类型参数,为什么 type[N] 与其专用版本不匹配----模板<类 T>类 S<T[]>
- C++ 模板:重载时找不到基类类型参数方法