【问题标题】:passing std::array to a function: default value将 std::array 传递给函数:默认值
【发布时间】:2015-01-11 20:30:14
【问题描述】:

我的函数签名如下:

void analyze(Image * x, std::array<bool, 4> smooth);

如果用户没有在调用中明确设置它,我想要给这个数组平滑一个默认值。所以我尝试了类似的方法:

std::array<bool, 4> smooth = std::array<bool, 4>
                               ({true, true, true, false}));
void analyze(Image * x, std::array<bool, 4> smooth = std::array<bool, 4>(({true, true, true, false})));

无论我尝试什么,我都无法编译它。上面的例子说“错误:预期的表达式”。

【问题讨论】:

  • 第一个版本运行良好:goo.gl/47WCPj。您使用的是较旧的编译器吗?
  • 去掉括号。
  • 不是 stl 数组。它是std::array。 STL 没有array 类模板。
  • @Luca +1 提问,但请记住 STL 不是标准 C++ 库; (我有时也说错了,因为很多人都有)。请注意,在您的示例中,较短的案例可以更具可读性并且适合没有滚动条的单行。总是试着问最小的问题。如果一个 2 元素数组用于说明这一点,为什么要使用 4 个元素?如果int 可以代替bool 来表达观点,那么整数12truefalse 更简洁。

标签: c++ c++11 std


【解决方案1】:

这行得通:

void analyze(Image * x, std::array<bool, 4> smooth = std::array<bool, 4>({true, true, true, false}));

这很有效:

void analyze(Image * x, std::array<bool, 4> smooth = std::array<bool, 4>{true, true, true, false});

它使用初始化列表初始化数组。您的代码有额外的括号。

【讨论】:

  • 一定是带有clang的东西......尝试第二个版本会给出预期的'('用于函数样式转换或类型构造
  • @Luca : clang 的版本是什么?
  • Apple LLVM 版本 6.0 (clang-600.0.54)(基于 LLVM 3.5svn)
【解决方案2】:

听起来问题出在你的编译器上。 这是 C++11 之前的解决方案:

void analyze(Image* x, std::bitset<4> smooth = std::bitset("1110"));

你也可以用unsigned long long初始化std::bitsetstd::bitset(14ull)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    相关资源
    最近更新 更多