gpt4 book ai didi

c++ - 有什么方法可以在旧版本的 c++(c++11 之前)中实现初始化列表(某种)?

转载 作者:太空狗 更新时间:2023-10-29 22:54:20 26 4
gpt4 key购买 nike

我已经尝试在旧版本的 c++ 中实现(有点 :) 初始化列表。像下面..

#include <vector>
#include <cstdarg>
#include <iostream>

using namespace std;

template <class T>
vector <T> VEC_VA(size_t argCount,T arg1, ... )
{
va_list arguments;
vector <T> sList;

va_start ( arguments, argCount);
for ( int x = 0; x < (int)argCount; x++ )
sList.push_back(va_arg ( arguments, T));
va_end ( arguments );

return sList;
}

struct Test
{
Test(int _x,std::string _s):x(_x),s(_s){}
int x;
std::string s;
};

void methodWithArgs(vector<Test> testObjs)
{
cout<<"Size:"<<testObjs.size()<<endl;
for (std::vector<Test>::const_iterator it = testObjs.begin();it != testObjs.end();++it)
std::cout << it->x <<":"<< it->s.c_str()<< std::endl;
}

int main()
{
methodWithArgs(VEC_VA(2,Test(1,"one"),Test(2,"two")));
return 0;
}

但这种实现适用于 Visual Studio 2012 (v11.0)。但在 Linux g++ 编译器中没有。并以错误结束:“无法通过‘...’传递不可平凡复制类型‘struct Test’的对象”

那么有什么更好的主意吗?

最佳答案

如果您愿意接受稍微不同的语法,那么您所需要的只是一个返回 vector 引用的 vector::push_back() 版本。像这样:

#include <vector>
#include <iostream>

template<typename T>
class VEC_VA_HELP {
std::vector<T> vector;
public:
VEC_VA_HELP(T arg1) : vector() { vector.push_back(arg1); }
VEC_VA_HELP &operator()(T arg) { vector.push_back(arg); return *this; }
operator std::vector<T> &() { return vector; }
};
template<typename T>
VEC_VA_HELP<T> VEC_VA(T arg1) { return VEC_VA_HELP<T>(arg1); }

struct Test {
Test(int _x) : x(_x) {}
int x;
};

void methodWithArgs(std::vector<Test> const &testObjs) {
std::cout << testObjs.size() << std::endl;
for (std::vector<Test>::const_iterator it = testObjs.begin();
it != testObjs.end();
++it)
std::cout << it->x << std::endl;
}

int
main(void)
{
methodWithArgs(VEC_VA(Test(1))(Test(2))(Test(3)));
return 0;
}

我也想到了递归模板,但我不确定它们的语法有多清晰。另见 this question关于重载逗号运算符。

关于c++ - 有什么方法可以在旧版本的 c++(c++11 之前)中实现初始化列表(某种)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56340938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com