c++ - 使此 C++ 代码通用

标签 c++ c++11 c++14 c++17

我正在尝试使代码片段通用,但我很难做到这一点,因为我不完全理解代码中使用的技术是如何工作的。

我从另一个问题得到代码:C++17 construct array in stack using choosen constructor (same constructor parameter values for each array entry)

这里是基于这篇文章的第一个响应的代码,由于某种原因不能处理大于 88 的大小: http://ideone.com/WDlNwd

#include <iostream>
#include <utility>

struct A1 {
    A1() {
        printf("A1() called\n");
    }

    A1(std::size_t i) {
        printf("A1(%d) called\n", i);
    }

    A1(std::size_t i, std::size_t j) {
        printf("A1(%d, %d) called\n", i, j);
    }
};

struct A2 {
    A2(std::size_t i, std::size_t j, double k) {
        printf("A2(%d, %d, %lf) called\n", i, j, k);
    }
};

template <class T, size_t Size>
class B {
    template<typename Arg1, typename ...Args, size_t... Is>
    B(std::index_sequence<Is...>, const Arg1 &arg1, const Args &...args) :
    tab{ {(void(Is), arg1), args... }... }
    {}

    public:

    T tab[Size];

    B() = default;

    template<typename ...Args>
    B(const Args &...args)
        : B(std::make_index_sequence<Size>(), args...) {}
};

int main() {
    static constexpr size_t Size = 100;
    B<A1, Size> b1(11, 17);
    B<A1, Size> b1a(11);
    B<A1, Size> b1b;
    B<A2, Size> b2(11, 17, 1.2);
    return 0;
}

谢谢

最佳答案

答案与the answer you got on the last one基本相同.唯一的区别是您必须特殊情况下传递零参数。并调整index_sequence参数的顺序:

struct B {
    A tab[100];

    //Note: feel free to use SFINAE to make this go away
    //if `A` is not default-constructible.
    B() = default;

    template<typename ...Args>
    B(const Args &...args)
        : B(std::make_index_sequence<100>(), args...) {}

private:

    template<typename Arg1, typename ...Args, size_t... Is>
    B(std::index_sequence<Is...>, const Arg1 &arg1, const Args &...args)
        : tab{ {(void(Is), arg1), args... }... } {}
};

关于c++ - 使此 C++ 代码通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41429656/

相关文章:

c++ - C++ 11:将 vector 元素作为线程传递到线程函数中

c++ - 使 C++ std::string 在指定字符处结束?

c++ - 是否允许编译器省略对指针的 &* 运算符的组合调用?

c++ - 错误 : cannot deduce 'auto' type (initializer required)

c++ - 如何在 QT GUI 应用程序中进行正确的线程处理?

c++ - 究竟什么时候复制返回值

c++ - 如何将矩阵提升为具有多个线程的幂?

C++14 堆栈分配的共享指针

c++ - sqlite 表代码管理器?

C++ 初始值设定项列表与 union ,为什么不同的结果?