Using std::map where V has no usable default constructor

后端 未结 9 1643
予麋鹿
予麋鹿 2020-12-05 13:11

I have a symbol table implemented as a std::map. For the value, there is no way to legitimately construct an instance of the value type via a default constructo

9条回答
  •  佛祖请我去吃肉
    2020-12-05 13:27

    you could specialize std::map for your value-type. I'm not saying it's a good idea, but it can be done. I specialized scoped_ptr's dtor to fclose instead of delete.

    Something like:

     template
     my_value_type& std::map::operator[](const K& k) 
     {
       //...
     }
    

    This should allow you to insert the code you want into operator[] for your type. Unfortunately, I do not know of a way in current c++ to return only r values. In c++0x you might be able to use:

     template
     my_value_type&& std::map::operator[](const K& k) 
     {
       //...
     }
    

    This will return an R-value reference (&&).

提交回复
热议问题