[英]Extended initializer lists and arrays
我有簡單的功能,如:
void fun(vector<int> vec)
{
//...
}
void fun(int* smth)
{
//...
}
當我在我的程序中寫字時沒有。
fun({2,3});
它讓我覺得有趣的矢量參數我知道它是在新的C ++擴展初始化列表中,但我想使用新的C ++並告訴編譯器這只是一個int的數組我怎么能這樣做?
編輯:
在1行中做它會很好:)
你不能初始化一個帶有數組的指針,因為指針不是一個數組(盡管在某些情況下會出現這種情況,但事實並非如此)。
您必須將指針傳遞給預先存在的數組。 或者,使用vector
過載 - 當然,你更喜歡這個嗎?! 如果兩個函數做不同的事情,那么為什么它們彼此重載(即為什么重要 )?
制作別名模板
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}));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.