使模板类获取另一个类<T>并将其视为数据类型 (C++)

Making template class get another class as <T> and consider it as data type (C++)

本文关键字:数据类型 C++ 获取 另一个 lt gt      更新时间:2023-10-16

我想做一些不寻常的事情。我有一个类模板:

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