通过基类构造函数从驱动类模板值

时间:2017-12-12 15:55:28

标签: c++ templates inheritance

我有这个代码,我觉得应该可行,但事实并非如此!

 class base
 {
     std::array<uint8_t, 8> m_ID;
 public:
     base(std::array<uint8_t, 8> id) :m_ID(id)
     {

     }
 }
 template<char ...Ts>
 class derived:base(Ts...)
 {
 }
 class MyClass: public derived<'1','2','3','4','5','6','7','8'>
 {
 }

我该怎么做?我的想法是我可以从模板值传递ID值。

我收到MyClass不完整的错误。 (不允许使用不完整的类型)

1 个答案:

答案 0 :(得分:3)

您只需要正确调用基类构造函数:

#include <array>
#include <cstdint>

 class base
 {
     std::array<std::uint8_t, 8> m_ID;
 public:
     base(std::array<std::uint8_t, 8> id) :m_ID(id)
     {

     }
 };

 template<char ...Ts>
 class derived: public base
 {
    public:
    derived() : base{ { Ts... } } { }
 };

class MyClass: public derived<'1','2','3','4','5','6','7','8'>
 {
 };

 int main() {
    MyClass d;
 }

请注意,在构造函数初始化列表中,需要使用内部大括号将单个uint8_t转换为数组。