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

标签 c++ initializer-list

我已经尝试在旧版本的 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/

相关文章:

c++ - 希望它仅从末尾修剪我的 TCHAR *

c++ - C++ 命名空间中的内联函数

c++ - 在初始化列表中复制构造

c++ - 尝试使用初始化器列表来初始化类的成员值时出现编译错误

C++ 函数重载和 initializer_list 构造函数

c++ - 命中断点错误

c++ - cmake 找不到 boost 库,因为它查找了错误的文件名

c++ - 为什么 C++ 中的 main() 没有重载以使用 std::string?

c++ - 是否有必要在构造函数初始化列表中调用默认构造函数?

arrays - 转换匿名数组初始值设定项列表