boost :: variant for boost ::任意大小的数组

mik*_*sol 6 c++ arrays boost

我想创造一个boost::variant精神

typedef boost::variant<boost::array<int, 1>, boost::array<int, 2>, boost::array<int, 3>, ... > any_int_array;
Run Code Online (Sandbox Code Playgroud)

一般化为N模板的第二个值.换句话说,a boost::variant包含任何大小的数组.这可能吗?

请注意,在上面的示例中,boost::array是我的一个案例,但对于将单个int值作为模板参数的任何类,它都需要是一个可行的解决方案.

seh*_*ehe 2

既然您正在谈论具有静态已知容量的类型,那么您不能通过一些模板元编程来摆脱这个困境吗?

住在科里鲁

#include <boost/variant.hpp>
#include <boost/array.hpp>
#include <bitset>
#include <iostream>

template <template <typename, size_t> class T, typename V, size_t N>
    void foo(T<V, N> const& something)
    {
        std::cout << __LINE__ << ": " << __PRETTY_FUNCTION__ << "\n";
    }

template <template <size_t> class T, size_t N>
    void foo(T<N> const& something)
    {
        std::cout << __LINE__ << ": " << __PRETTY_FUNCTION__ << "\n";
    }

int main()
{
    boost::array<int, 67> a;
    boost::array<double, 78> b;
    std::bitset<47> c;

    foo(a);
    foo(b);
    foo(c);
}
Run Code Online (Sandbox Code Playgroud)

印刷

9: void foo(const T<V, N> &) [T = array, V = int, N = 67]
9: void foo(const T<V, N> &) [T = array, V = double, N = 78]
15: void foo(const T<N> &) [T = bitset, N = 47]
Run Code Online (Sandbox Code Playgroud)

更新

Brainwave:我刚刚意识到它std::array<>指定为POD(琐碎)类型。因此,布局必须是标准的,并且大小必须与等效数组相同T[N]。由于这些限制,只要 和,您就可以安全地将任何类型转换std::array<T, M>std::array<T, N>&(具有匹配的const/易失性限定) 。N>0N<=M

相反,所需的存储

variant<array<T, 1>, array<T, 1>, array<T, 1>, .... array<T, 1000> >
Run Code Online (Sandbox Code Playgroud)

类型鉴别器的开销总是至少 为 + ( )。如果仅维度不同,则区分所有其他不同的 array<> 实例没有任何好处sizeof array<T, 1000>which()