我正在嘗試使用函數模板foo
將參數轉換爲initializer_list
。但是,它轉換的initializer_list
具有奇怪的值,與輸入參數不一樣。在模板函數中使用initializer_list
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
template<class T>
void func(std::initializer_list<T> a_args)
{
if (a_args.begin() != a_args.end())
{
auto last = prev(a_args.end());
copy(a_args.begin(), last, ostream_iterator<int>(cout, ","));
cout << *last;
}
cout << endl;
}
template<class T, class ...Args>
struct first_of
{
typedef T type;
};
template<class ...Args>
initializer_list<typename first_of<Args...>::type> foo(Args&&... args)
{
return { forward<Args>(args)... };
}
int main()
{
func({1,2,3});
auto x = foo(1,2,3);
func(x); //this should be the same as func({1,2,3}) but not.
}
的輸出中如下:
1,2,3
-326483696,32767,0
這裏有什麼問題?
初始化列表並不意味着舉行,以後使用。 – chris
複製'initializer_list'(例如從函數返回時)不會複製基礎元素。 – jrok