winrt::single_threaded_observable_vector 함수 템플릿(C++/WinRT)

관찰 가능한 컬렉션을 구현하는 형식의 개체를 만들고 반환하는 함수 템플릿입니다. 개체는 IObservableVector로 반환되며 반환된 개체의 함수 및 속성을 호출하는 인터페이스입니다.

필요에 따라 기존 std::vectorrvalue를 함수에 전달할 수 있습니다. 즉, 임시 개체를 전달하거나 lvalue에서 std::move를 호출할 수 있습니다.

자세한 정보 및 코드 예제는 C++/WinRT를 사용하는 컬렉션을 참조하세요.

구문

template <typename T, typename Allocator = std::allocator<T>>
winrt::Windows::Foundation::Collections::IObservableVector<T> single_threaded_observable_vector(std::vector<T, Allocator>&& values = {})

템플릿 매개 변수

typename T 컬렉션 요소의 형식입니다.

typename Allocator 컬렉션을 초기화하는 벡터의 할당자 형식이며, 전달하면 기본 할당자입니다.

매개 변수

values컬렉션 개체의 요소를 초기화할 std::vector 형식의 rvalue에 대한 선택적 참조입니다.

반환 값

새 컬렉션 개체를 나타내는 IObservableVector 입니다.

요구 사항

지원되는 최소 SDK: Windows SDK 버전 10.0.17763.0(Windows 10, 버전 1809)

네임스페이스: winrt

헤더: %WindowsSdkDir%IncludeWindowsTargetPlatformVersion<>\cppwinrt\winrt\base.h(기본적으로 포함)

이전 버전의 Windows SDK가 있는 경우

Windows SDK 버전 10.0.17763.0(Windows 10, 버전 1809) 이상이 없는 경우 IObservableVectorT<>의 유용한 범용 구현 역할을 하려면 관찰 가능한 고유한 벡터 템플릿을 구현해야 합니다. 다음은 single_threaded_observable_vector< T>라는 클래스의 목록입니다. 포함된 Windows SDK 버전에 있는 경우 아래 형식에서 winrt::single_threaded_observable_vector 쉽게 전환할 수 있습니다.

// single_threaded_observable_vector.h
#pragma once

namespace winrt::Bookstore::implementation
{
    using namespace Windows::Foundation::Collections;

    template <typename T>
    struct single_threaded_observable_vector : implements<single_threaded_observable_vector<T>,
        IObservableVector<T>,
        IVector<T>,
        IVectorView<T>,
        IIterable<T>>
    {
        event_token VectorChanged(VectorChangedEventHandler<T> const& handler)
        {
            return m_changed.add(handler);
        }

        void VectorChanged(event_token const cookie)
        {
            m_changed.remove(cookie);
        }

        T GetAt(uint32_t const index) const
        {
            if (index >= m_values.size())
            {
                throw hresult_out_of_bounds();
            }

            return m_values[index];
        }

        uint32_t Size() const noexcept
        {
            return static_cast<uint32_t>(m_values.size());
        }

        IVectorView<T> GetView()
        {
            return *this;
        }

        bool IndexOf(T const& value, uint32_t& index) const noexcept
        {
            index = static_cast<uint32_t>(std::find(m_values.begin(), m_values.end(), value) - m_values.begin());
            return index < m_values.size();
        }

        void SetAt(uint32_t const index, T const& value)
        {
            if (index >= m_values.size())
            {
                throw hresult_out_of_bounds();
            }

            ++m_version;
            m_values[index] = value;
            m_changed(*this, make<args>(CollectionChange::ItemChanged, index));
        }

        void InsertAt(uint32_t const index, T const& value)
        {
            if (index > m_values.size())
            {
                throw hresult_out_of_bounds();
            }

            ++m_version;
            m_values.insert(m_values.begin() + index, value);
            m_changed(*this, make<args>(CollectionChange::ItemInserted, index));
        }

        void RemoveAt(uint32_t const index)
        {
            if (index >= m_values.size())
            {
                throw hresult_out_of_bounds();
            }

            ++m_version;
            m_values.erase(m_values.begin() + index);
            m_changed(*this, make<args>(CollectionChange::ItemRemoved, index));
        }

        void Append(T const& value)
        {
            ++m_version;
            m_values.push_back(value);
            m_changed(*this, make<args>(CollectionChange::ItemInserted, Size() - 1));
        }

        void RemoveAtEnd()
        {
            if (m_values.empty())
            {
                throw hresult_out_of_bounds();
            }

            ++m_version;
            m_values.pop_back();
            m_changed(*this, make<args>(CollectionChange::ItemRemoved, Size()));
        }

        void Clear() noexcept
        {
            ++m_version;
            m_values.clear();
            m_changed(*this, make<args>(CollectionChange::Reset, 0));
        }

        uint32_t GetMany(uint32_t const startIndex, array_view<T> values) const
        {
            if (startIndex >= m_values.size())
            {
                return 0;
            }

            uint32_t actual = static_cast<uint32_t>(m_values.size() - startIndex);

            if (actual > values.size())
            {
                actual = values.size();
            }

            std::copy_n(m_values.begin() + startIndex, actual, values.begin());
            return actual;
        }

        void ReplaceAll(array_view<T const> value)
        {
            ++m_version;
            m_values.assign(value.begin(), value.end());
            m_changed(*this, make<args>(CollectionChange::Reset, 0));
        }

        IIterator<T> First()
        {
            return make<iterator>(this);
        }

    private:

        std::vector<T> m_values;
        event<VectorChangedEventHandler<T>> m_changed;
        uint32_t m_version{};

        struct args : implements<args, IVectorChangedEventArgs>
        {
            args(CollectionChange const change, uint32_t const index) :
                m_change(change),
                m_index(index)
            {
            }

            CollectionChange CollectionChange() const
            {
                return m_change;
            }

            uint32_t Index() const
            {
                return m_index;
            }

        private:

            Windows::Foundation::Collections::CollectionChange const m_change{};
            uint32_t const m_index{};
        };

        struct iterator : implements<iterator, IIterator<T>>
        {
            explicit iterator(single_threaded_observable_vector<T>* owner) noexcept :
            m_version(owner->m_version),
                m_current(owner->m_values.begin()),
                m_end(owner->m_values.end())
            {
                m_owner.copy_from(owner);
            }

            void abi_enter() const
            {
                if (m_version != m_owner->m_version)
                {
                    throw hresult_changed_state();
                }
            }

            T Current() const
            {
                if (m_current == m_end)
                {
                    throw hresult_out_of_bounds();
                }

                return*m_current;
            }

            bool HasCurrent() const noexcept
            {
                return m_current != m_end;
            }

            bool MoveNext() noexcept
            {
                if (m_current != m_end)
                {
                    ++m_current;
                }

                return HasCurrent();
            }

            uint32_t GetMany(array_view<T> values)
            {
                uint32_t actual = static_cast<uint32_t>(std::distance(m_current, m_end));

                if (actual > values.size())
                {
                    actual = values.size();
                }

                std::copy_n(m_current, actual, values.begin());
                std::advance(m_current, actual);
                return actual;
            }

        private:

            com_ptr<single_threaded_observable_vector<T>> m_owner;
            uint32_t const m_version;
            typename std::vector<T>::const_iterator m_current;
            typename std::vector<T>::const_iterator const m_end;
        };
    };
}

Append 함수는 IObservableVectorT<>::VectorChanged 이벤트를 발생하는 방법을 보여 줍니다.

m_changed(*this, make<args>(CollectionChange::ItemInserted, Size() - 1));

이벤트 인수는 요소가 삽입되었음을 나타내며 해당 인덱스(이 경우 마지막 요소)도 나타냅니다. 이러한 인수를 사용하면 XAML 항목 컨트롤이 이벤트에 응답하고 최적의 방법으로 자신을 새로 고칠 수 있습니다.

위에서 정의한 형식의 인스턴스를 만드는 방법입니다. winrt::single_threaded_observable_vector 팩터리 함수 템플릿을 호출하는 대신 winrt::make를 호출하여 컬렉션 개체를 만듭니다.

#include "single_threaded_observable_vector.h"
...
winrt::Windows::Foundation::Collections::IVector<winrt::Windows::Foundation::IInspectable> m_bookSkus;
...
m_bookSkus = winrt::make<winrt::Bookstore::implementation::single_threaded_observable_vector<winrt::Windows::Foundation::IInspectable>>();

참고 항목