Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extended initializer lists and arrays

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 :)

like image 258
Dawid Avatar asked Nov 25 '12 20:11

Dawid


2 Answers

You can't initialise a pointer with an array, because a pointer is not an array (despite the appearance in some situations that this is occuring, it is not).

You'll have to pass a pointer to a pre-existing array. Alternatively, use the vector overload — surely, you prefer this one anyway?! And if the two functions do different things then why are they overloads of one another (i.e. why does it matter)?

like image 161
Lightness Races in Orbit Avatar answered Oct 22 '22 15:10

Lightness Races in Orbit


Make an alias template

template<typename T>
using identity = T;

So you can write

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

This is not good programming though, because in your function you have no way to know the size of the array pointed to. This should be passed explicitly to the function, if the function is supposed to work with a list of elements. If you want to process arrays, consider using something like llvm::ArrayRef<T> or create your own

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}));
}
like image 6
Johannes Schaub - litb Avatar answered Oct 22 '22 13:10

Johannes Schaub - litb