开发者

2d STL vector typeid

开发者 https://www.devze.com 2023-02-12 11:58 出处:网络
I have various 2D vectors and I want to query their differing types at runtime. It appears this is possible on an \"empty\" vector, e.g.:

I have various 2D vectors and I want to query their differing types at runtime.

It appears this is possible on an "empty" vector, e.g.:

vector<vector<float> > myVec;
cout << (typeid(myVec[0][0]).name() << endl;

The above returns "float" although I was expecting an exception as I've开发者_StackOverflow中文版 not pushed back any elements.

Is it just luck that when accessing the memory at [0][0] without any bounds checking or iterator it succeeds? Or does the vector allocate some baseline storage when it is declared?


Since float does not have any virtual methods, the compiler can evaluate typeid(some_float_object) statically without looking at the actual expression, just its static type. According to section 5.2.8 of the C++ standard (current C++0x draft), the compiler is not even allowed to evaluate the expression.

0

精彩评论

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