开发者

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

开发者 https://www.devze.com 2023-03-10 12:38 出处:网络
I suppose to do some unusual stuff. I have a class template: template<class T> class CFile I want to build another class which would have a member of int type,

I suppose to do some unusual stuff. I have a class template:

template<class T> class CFile

I want to build another class which would have a member of int type,

class foo
{
private:
     int memb;
}

when I pass the "foo" class as "< T >" to "CFile", foo is supposed to simply act as integer. I need ideas how to implement it only with internal logic in foo, without changing CFile (CFile is not allowed to contain any logic which extracts the int member from the class).

It's for a task in college, so I should not change the rules given to me. It should look like this:

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 开发者_JS百科< 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");

}

Thanks.


What I think you're trying to do is for class foo to act as an integer. For this effect you need to provide:

  • A constructor that can create a foo from an int.
  • An overloaded cast operator that implicitly casts your foo class to an int.

You would have something like this:

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


If CFile uses streams to write to the file then you only need to implement operator<< in the Foo class.

Something like:

ofstream file;

file.open("file.txt"); //open a file

file<<T; //write to it

file.close(); //close it

in the CFile and this added to Foo:

ofstream &operator<<(ofstream &stream, Foo& foo)
{
  stream << foo.memb;

  return stream; 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消