5

I have simple function such as:

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

void fun(int* smth)
{
//...
}

No when i write in my program.

fun({2,3});

It calls me fun with vector argument i know it is in new C++ extended initializer lists but i would like to use new C++ and tell compiler that this is only a array of int's how i can do it?

EDIT:

It would be nice to do it in 1 line :)

4

2 に答える 2

8

ポインターは配列ではないため、配列でポインターを初期化することはできません (状況によっては、これが発生しているように見えますが、そうではありません)。

既存の配列へのポインターを渡す必要があります。または、オーバーロードを使用してvectorください — 確かに、とにかくこれを好みますか?! そして、2 つの関数が異なることを行う場合、なぜそれらは相互にオーバーロードされるのでしょうか (つまり、なぜそれが重要なのですか)?

于 2012-11-25T20:44:54.170 に答える
6

エイリアス テンプレートを作成する

template<typename T>
using identity = T;

だからあなたは書くことができます

fun(identity<int[]>{1,2});

ただし、これは適切なプログラミングではありません。関数では、指している配列のサイズを知る方法がないためです。関数が要素のリストで動作することになっている場合は、これを関数に明示的に渡す必要があります。配列を処理したい場合は、次のようなものを使用するか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}));
}
于 2012-11-25T20:47:06.570 に答える