使模板类获取另一个类<T>并将其视为数据类型 (C++)
Making template class get another class as <T> and consider it as data type (C++)
我想做一些不寻常的事情。我有一个类模板:
template<class T> class CFile
我想建立另一个类,它将有一个int类型的成员,
class foo
{
private:
int memb;
}
当我将"foo"类作为"<T>"传递给"CFile"时,foo
应该只是作为整数。我需要如何在foo
中仅使用内部逻辑实现它,而不更改CFile
(CFile不允许包含任何从类中提取int成员的逻辑)。
这是大学里的一项任务,所以我不应该改变给我的规则。它应该是这样的:
class foo
{
int memb;
}
int main()
{
foo myFoo;
// The ctor of CFile takes a file path and opens the file. After that it can write
// members from type < T > to the file. I need the CFile to write the memb member to
// the file (Remember that the CFile is passed as < T >
CFile<foo> file("c:\file.txt");
}
谢谢。
我认为您要做的是让class foo
充当一个整数。为此效果,您需要提供:
- 可以从
int
创建foo
的构造函数 - 一个重载的强制转换运算符,它将
foo
类隐式强制转换为int
你会有这样的东西:
class foo {
public:
foo() {} // Create a foo without initializing it
foo(const int &memb): _memb(memb) {} // Create and initialize a foo
operator int&() {return _memb;} // If foo is not constant
operator const int&() const {return _memb;} // If foo is constant
private:
int _memb;
};
如果CFile使用流写入文件,那么您只需要实现运算符<lt;在Foo类中。
类似于:
ofstream file;
file.open("file.txt"); //open a file
file<<T; //write to it
file.close(); //close it
在CFile中,并将其添加到Foo:
ofstream &operator<<(ofstream &stream, Foo& foo)
{
stream << foo.memb;
return stream;
}
相关文章:
- 防止主数据类型C++的隐式转换
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在C++中打印指向不同基元数据类型的指针的内存地址
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何计算数据类型的范围,例如int
- C++中数据类型修饰符的顺序
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 特定数据类型的模板类
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 如何获取C++字符数据类型的地址
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- 构造智能点数据类型以及普通数据类型的通用方法
- 如何使映射键具有两种不同的数据类型?
- 数据类型"struct seq<0, 1, 2>{}"含义是什么?
- 如何在不破坏现有应用程序的情况下更改 API 中 stl 容器的数据类型?
- Static_cast转换为错误的数据类型,但结果仍然正确?
- 使用 Boost.Spirit 解析具有混合数据类型的 OBJ 文件?