I have some types like the following:

struct Order_t;
using SpOrder_t = std::shared_ptr<Order_t>;
using CpOrder_t = std::shared_ptr<const Order_t>;
using SomeOrders_t = std::vector<SpOrder_t>;
using ConstOrders_t = std::vector<CpOrder_t>;

I want to directly assign from a SomeOrders_t to a ConstOrders_t, but the compiler said those are different types:

SomeOrders_t _cur_ords;

ConstOrders_t TradingOrders() {
    return _cur_ords;
};

Is there a method to let me assign directly? Or do I have to use a loop and assign them one by one?

2

There are 2 best solutions below

4
molbdnilo On BEST ANSWER

If T is a template with one type parameter, and u and v are different types, then T<u> and T<v> are different (and unrelated) types.
Even if there is an implicit conversion from u to v, there is no (default) implicit conversion from T<u> to T<v>.
(std::shared_ptr has converting constructors and assignments that enable the conversion from shared_ptr<Order_t> to shared_ptr<const Order_t>, which makes them behave like Order_t* and const Order_t*.)

Making the conversion explicit is pretty trivial, though:

ConstOrders_t TradingOrders() {
    return { _cur_ords.begin(), _cur_ords.end() };
};
3
DipStax On

The definition of a shared_ptr is declared as:

template<class T>
std::shared_ptr<T>

Defining T as const _T or _T generate two different type (if you wan't to see how it work check this documentation), but you can actually change the type by casting it using static_pointer_cast. In your case it would look like:

SomeOrders_t _cur_ords;

ConstOrders_t TradingOrders() {
    return static_pointer_cast<const Order_T>(_cur_ords);
};