Using decltype to return an iterator

I have this class:

template <typename T>
class Hybrid
{
public:
    Hybrid() : m_activeStackSize(0) {}

private:
    std::list<T> data;

    size_t m_activeStackSize;

    auto internal_peek() -> decltype(data)::iterator
    {
        if (m_activeStackSize) // peek from stack
        {
            decltype(data)::iterator itr = data.end();
            std::advance(itr, -1);
            return itr;
        }
        else //peek from queue
        {
            decltype(data)::iterator itr = data.begin();
            return itr;
        }
    }
};

When I try to compile this in Microsoft Visual Studio 2015, I get:

main.cpp (12): error C3646: 'iterator': unknown override specifier

I do not understand why it will not allow me to return the iteratortype std::list<T>while the body code is:

decltype(data)::iterator itr = data.end();

and

decltype(data)::iterator itr = data.begin();

Compile successfully.

How can I successfully return std::list iteratorusing decltypeexplicitly?

Uninstall -> decltype(data)::iteratorsuccessfully compiled.

Edit: Compiling with GCC and adding typenamefor each decltype compiles fine , MSVC still doesn't work.

+4
source share
2 answers

decltype(data)::iterator . , typename.

auto internal_peek() -> typename decltype(data)::iterator
                       //  ^^^^^ here
{
    if (m_activeStackSize) // peek from stack
    {
        typename decltype(data)::iterator itr = data.end();
        // ^^^^^ and here
        std::advance(itr, -1);
        return itr;
    }
    else //peek from queue
    {
        typename decltype(data)::iterator itr = data.begin();
        // ^^^^^ and here
        return itr;
    }
}

MSVC.

// Declare iterator as a type.
using iterator = typename std::list<T>::iterator;

iterator internal_peek()
{
    if (m_activeStackSize) // peek from stack
    {
        iterator itr = data.end();
        std::advance(itr, -1);
        return itr;
    }
    else //peek from queue
    {
        iterator itr = data.begin();
        return itr;
    }
}
+6

++ 14 decltype(). ++ 14 ( , MSVC ++ 14):

   auto internal_peek()
    {
        if (m_activeStackSize) // peek from stack
        {
            auto itr = data.end();
            std::advance(itr, -1);
            return itr;
        }
        else //peek from queue
        {
            auto itr = data.begin();
            return itr;
        }
    }
+2

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


All Articles