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 :)
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)?
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}));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With