【问题标题】:Initialise template within derived constructor initialisation list在派生构造函数初始化列表中初始化模板
【发布时间】:2016-04-08 18:52:59
【问题描述】:

Foo 继承 std::array<int, 2>。是否可以将数组填充到 Foo 的构造函数的初始化列表中?

如果是这样,以下语法的有效替代方法是什么?

// Foo is always an array of 2 ints
struct Foo: std::array<int, 2>
{
    Foo() {}
    Foo(const int & x, const int & y) : std::array<int, 2> { x, y } {}
}

我尝试添加一对额外的大括号,它适用于 g++,但不适用于 VC2015 编译器:

#include <array>
#include <iostream>

struct Foo : std::array<int, 2>
{
    Foo() {}
    Foo(const int & x, const int & y) : std::array<int, 2> {{ x, y }} {}
};

int main()
{
    Foo foo(5, 12);

    std::cout << foo[0] << std::endl;
    std::cout << foo[1] << std::endl;

    system("PAUSE");
}

并得到以下错误:https://i.gyazo.com/4dcbb68d619085461ef814a01b8c7d02.png

【问题讨论】:

  • 为什么Foo继承自std::array
  • 在我的应用程序中,它将是一个带有 GetX() SetY() 函数等的点/向量类。对我来说,这比带有 x,y,z 数据成员的结构更有意义,因为它允许我删除每个维度的重复代码。
  • 这当然取决于您如何设计事物。但我要说的是,继承并不是大多数工作的最佳工具(blog.codinghorror.com/inherits-nothing,而且与 C# 不同,大多数 C++ 标准库并不是真正设计用于继承的)。虽然您可以从std::array 继承,但请注意它没有virtual 函数,这意味着您几乎永远不会通过std::array 指针或引用与您的Foo 交互;但这没关系,因为std::array 的析构函数是非虚拟的,所以当你销毁你的对象时,你需要知道你真的有一个Foo
  • 但是在基类中没有任何virtual 方法,我个人认为没有太多使用继承的理由。
  • 最好的选择是什么?我试图避免使用 C 数组。

标签: c++ templates constructor initializer-list


【解决方案1】:

是的,您只需要一对额外的牙套:

struct Foo: std::array<int, 2> {
    Foo() {}
    Foo(const int & x, const int & y) : std::array<int, 2> {{ x, y }} {}
                                                           ^        ^
};

Live Demo

对于 VC++ 编译器,您需要一对括号而不是大括号:

struct Foo : std::array<int, 2> {
    Foo() {}
    Foo(const int & x, const int & y) : std::array<int, 2>({ x, y }) {}
                                                          ^        ^
};

【讨论】:

  • 不幸的是,这不起作用;请查看我编辑的问题。编辑:在 VS2015 中
  • 谢谢!您最新的编辑工作正常。标记为已解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-23
  • 1970-01-01
相关资源
最近更新 更多