| wmheric (119) | |
|
Hi all, I'm writing my own code for data manipulation on text files, where data are arranged as columns of (floating-point) numbers; I come across a class DataColumn which basically encapsulates a std::vector<double> for data storage. To make the code more flexible I'm using std::vector<>::size_type instead of ints or unsigneds.One of the constructors looks like this: DataColumn( std::vector<double>::size_type size );where size defines the size of the std::vector in the private field.Somewhere else in my program (e.g. in main()), I plan to do something likeDataColumn myCol(10);The compiler must complain, as it doesn't know what to do with DataColumn(int).But I learnt that for the STL std::vector, there is implicit conversion for the constructor explicit vector ( size_type n, /*blahblahblah*/ );so I can do std::vector<double> myVec(3);.--- One way to "teach" the compiler is defining my own DataColumn::DataColumn(int) which uses DataColumn::DataColumn(size_type) with a type cast. But this is cumbersome, and it pours type casts everywhere in my code...After some googling I found out that (http://www.glenmccl.com/ansi_033.htm) Bjarne Stroustrup did something extraordinary in the standard library as the workaround. Without worrying about the details in the library, are there any simpler ways to "teach" the compiler? Also, I don't see defining my own, say, my_size_type class which contains an implicit constructor plausible as it only carries the problem to another one: undefined actions like std::vector<double>(my_size_type).Thanks in advance. [EDITED] I also noticed a similar thread (http://www.cplusplus.com/forum/beginner/22570/), but it is not exactly asking for such solution. | |
|
Last edited on
|
|
| hamsterman (4227) | ||
Notice that size_type is typedefed as some basic type, like unsigned long. Some conversions are done by C++ implicitly and conversions between basic types include those. Sadly, I can't quote the standard exactly as I don't have it on my PC right now..
| ||
|
|
||
| wmheric (119) | |
|
Thanks for pointing that out! Silly me, it happens that in some other places in the code, some r-values of ints are being passed into the constructor. At least I have made one thing clear: it is the literals that are implicitly converted. | |
|
|
|
| hamsterman (4227) | |||
|
No, it sounds like you're still misunderstanding. You can do
And somewhere in <vector> there is a line typedef unsigned int size_type; so you can do all those things with size type too. (Except you can't do vector<int> vec = 5; because that constructor has been declared explicit).
| |||
|
|
|||