扩展初始化列表和数组

Daw*_*ozd 5 c++ arrays initializer-list c++11

我有简单的功能,如:

void fun(vector<int> vec)
{
//...
}

void fun(int* smth)
{
//...
}
Run Code Online (Sandbox Code Playgroud)

当我在我的程序中写字时没有.

fun({2,3});
Run Code Online (Sandbox Code Playgroud)

它让我觉得有趣的矢量参数我知道它是在新的C++扩展初始化列表中,但我想使用新的C++并告诉编译器这只是一个int的数组我怎么能这样做?

编辑:

在1行中做它会很好:)

Lig*_*ica 8

你不能初始化一个带有数组的指针,因为指针不是一个数组(尽管在某些情况下会出现这种情况,但事实并非如此).

您必须将指针传递给预先存在的数组.或者,使用vector过载 - 当然,你更喜欢这个吗?!如果两个函数做不同的事情,那么为什么它们彼此重载(即为什么重要)?


Joh*_*itb 6

制作别名模板

template<typename T>
using identity = T;
Run Code Online (Sandbox Code Playgroud)

所以你可以写

fun(identity<int[]>{1,2});
Run Code Online (Sandbox Code Playgroud)

这不是一个好的编程,因为在你的函数中你无法知道指向的数组的大小.如果函数应该与元素列表一起使用,则应该将其显式传递给函数.如果要处理数组,请考虑使用类似的东西llvm::ArrayRef<T>或创建自己的数组

struct array_ref {
public:
  template<int N>
  array_ref(const identity<int[N]> &n)
    :begin_(n), end_(n + N)
  { }

  array_ref(const std::vector<int>& n)
    :begin_(n.data()), end_(n.data() + n.size())
  { }

public:
  int const *begin() const { return begin_; }
  int const *end() const { return end_; }
  int size() const { return end_ - begin_; }

private:
  int const *begin_;
  int const *end_;
};

void fun(array_ref array) {
  ...
}

int main() {
  fun(array_ref(identity<int[]>{1,2}));
}
Run Code Online (Sandbox Code Playgroud)