Which do i use?

I am trying to remove const from an object, but it does not work. But if I use the old C-shaped code compilation code. So what casting should I use to achieve the same effect? I would not want to set the old way.

//file IntSet.h

#include "stdafx.h"
#pragma once
/*Class representing set of integers*/
template<class T>
class IntSet
{
private:
    T** myData_;
    std::size_t mySize_;
    std::size_t myIndex_;
public:
#pragma region ctor/dtor
    explicit IntSet();
    virtual ~IntSet();
#pragma endregion
#pragma region publicInterface
    IntSet makeUnion(const IntSet&)const;
    IntSet makeIntersection(const IntSet&)const;
    IntSet makeSymmetricDifference(const IntSet&)const;
    void insert(const T&);

#pragma endregion
};

//file IntSet_impl.h

#include "StdAfx.h"
#include "IntSet.h"

#pragma region ctor/dtor
template<class T>
IntSet<T>::IntSet():myData_(nullptr),
                    mySize_(0),
                    myIndex_(0)
{
}

IntSet<T>::~IntSet()
{
}
#pragma endregion

#pragma region publicInterface
template<class T>
void IntSet<T>::insert(const T& obj)
{
    /*Check if we are initialized*/
    if (mySize_ == 0)
    {
        mySize_ = 1;
        myData_ = new T*[mySize_];
    }
    /*Check if we have place to insert obj in.*/
    if (myIndex_ < mySize_)
    {//IS IT SAFE TO INCREMENT myIndex while assigning?
        myData_[myIndex_++] = &T(obj);//IF I DO IT THE OLD WAY IT WORKS
        return;
    }

    /*We didn't have enough place...*/
    T** tmp = new T*[mySize_];//for copying old to temporary basket
    std::copy(&myData_[0],&myData_[mySize_],&tmp[0]);

}
#pragma endregion

Thank.

+3
source share
5 answers

There is a special C ++ operator for working with const const_cast::

myData_[myIndex_++] = &const_cast<T>(obj);
+4
source

I assume this is what you are talking about:

    myData_[myIndex_++] = &T(obj);//IF I DO IT THE OLD WAY IT WORKS

. T(obj) , & , . , , ;.

, , . , ? , - ?

, , -

    myData_[myIndex_++] = new T(obj);

( delete .) ,

void IntSet<T>::insert(T& obj) // remove const

,

T const ** myData_;

. ( , , insert(3) .)

++. IntSet MakeUnion, makeIntersection makeSymmetricDifference std::vector<int> / std::set<int> std::set_union, std::set_intersection std::set_symmetric_difference.

+2

. , , :

T const ** myData_;

, , , , .

+1

? , ?

; const T& obj , T. , :

IntSet<int> int_set;
int_set.insert(1);
short foo= 2;
int_set.insert(foo);

IntSet<T>::insert , .

0

?

int * foo() {int x = 3; return & x; }

x? foo , x? , , .

-1

Source: https://habr.com/ru/post/1741147/


All Articles