如何专注于可变参数类模板

时间:2016-12-16 12:57:42

标签: c++ variadic-templates

以下示例代码说明了我的问题:

#include <array>
#include <vector>
#include <iostream>
#include <type_traits>

namespace Vector
{
    namespace Intern
    {
        template <typename T1, typename ...T2>
        struct Traits;

        // How can I specialize here so that Memory is being assigned properly??
        template <typename T1, int N>
        struct Traits<T1, int> {
            static constexpr bool Static = 1;
            using Memory = std::array<T1, N>;
        };

        template <typename T1>
        struct Traits<T1> {
            static constexpr bool Static = 0;
            using Memory = std::vector<T1>;
        };
    }

    template <typename T1, typename ...T2>
    class Object
    {
        public :
            void printd()
            {
                std::cout << "Is Static: " << Traits::Static << std::endl;
            }
        private:
            using Traits = Intern::Traits<T1, T2...>;
            using Memory = typename Traits::Memory;

            Memory m_memory;
    };

    template <typename T1, typename ...T2>
    static auto Create(T2&& ...ln) -> decltype(auto)
    {
        return new Object<T1, T2...>();
    }
}

int main()
{
    auto static_vector = Vector::Create<int>(10);
    static_vector->printd();

    auto active_vector = Vector::Create<int>(  );
    active_vector->printd();
}

我想知道如何专门化traits struct,以便在上面的例子中将Memory类型正确地指定为std :: array,其中N设置为10。

2 个答案:

答案 0 :(得分:1)

您不能直接使用整数,但可以将整数包装到一个类型中。这可以使用 例如std::integral_constant

template <typename T1, typename T2, int N>
struct Traits<T1, std::integral_constant<T2, N>> {
    static constexpr bool Static = 1;
    using Memory = std::array<T1, N>;
};

template <typename T1>
struct Traits<T1> {
    static constexpr bool Static = 0;
    using Memory = std::vector<T1>;
};


auto static_vector = Vector::Create<int, std::integral_constant<int, 10>>();

答案 1 :(得分:1)

保持简单:

#include <array>
#include <vector>
#include <iostream>
#include <type_traits>

namespace Vector
{
    struct VariableSize {};
    template<std::size_t N> struct FixedSize {};

    template<typename T, std::size_t N>
    auto Create(FixedSize<N>)
    {
        return std::array<T, N>();
    }

    template<typename T, std::size_t N>
    auto Create(VariableSize)
    {
        return std::vector<T>();
    }
}

int main()
{
    auto static_vector = Vector::Create<int>(Vector::FixedSize<10>());

    auto active_vector = Vector::Create<int>(Vector::VariableSize());
}
相关问题