c++ template casting

后端 未结 7 1153
伪装坚强ぢ
伪装坚强ぢ 2021-01-06 13:48

I\'m a little lost in how to cast templates. I have a function foo which takes a parameter of type ParamVector*. I would like to pass in a P

相关标签:
7条回答
  • 2021-01-06 14:24

    Notice that when you do an implicit cast, what the compiler can do without your help (I mean, without additional code) is just reference-upcast. That means that, seeing the object as a reference (for cast purposes only, the nature of the object doesn't change of course), it can look at it as one of its ancestors. When you have two template instances, none of them is an ancestor of the other (neither they are necessarily in the same hierarchy). After trying that, the compiler looks for cast operators, constructors, etc. At this stage, probably a temporary object needs to be created, except when you're doing attribution and there's an attribution operator that fits.

    One solution to your problem would be to use a conversion constructor:

    template<class T> class ParamVector 
    {
    public:
        vector <T> gnome;
        vector <T> data_params;
    
        ParamVector()
        {
        }
        template <class T2> ParamVector(const ParamVector<T2> &source)
        {
            gnome.reserve(source.gnome.size());
            copy(source.gnome.begin(), source.gnome.end(), gnome.begin());
            data_params.reserve(source.data_params.size());
            copy(source.data_params.begin(), source.data_params.end(), data_params.begin());
        }
    };
    

    This would create a temporary object whenever you use an instance of the template and other is required. Not a good solution if you're dealing with large containers, the overhead isn't acceptable. Also, if you pass a template instance to a function that requires not an object but a reference, the compiler won't call the conversion constructor automatically (you have to do an explicit call).

    0 讨论(0)
提交回复
热议问题