gpt4 book ai didi

C++ 11通过引用函数传递可变数量的对象

转载 作者:行者123 更新时间:2023-11-30 03:23:42 25 4
gpt4 key购买 nike

我试图在 C++11 中通过引用传递可变数量的对象。

可变参数网络的 C 风格看起来不是很优雅,所以我尝试使用 std::initialiszer_list。

但是我找到的所有例子都是通过复制传递的,我写了一个简单的例子来说明我想要实现的目标:

//Example class for illustration purposes
class MyClass
{
public:
MyClass()
: m_id(0), m_idChecks(0)
{}
~MyClass(){}

int getId()
{
m_idChecks++;
return m_id;
}
int getIdChecks() const
{
return m_idChecks;
}

private:
int m_id;
int m_idChecks;
};


// I want to do something like this (pass the objects by reference):
// void test_initializerList(std::initializer_list<MyClass&> listClasses)
// But only pass by copy works:
void test_initializerList(std::initializer_list<MyClass> listClasses)
{
// Doing operations on copies of the object:
int sum = 0;
for(auto c : listClasses)
{
sum += c.getId();
}
std::cout << "\n id: " << sum;
}
void test()
{

MyClass c1;
MyClass c2;
MyClass c3;

test_initializerList({c1,c2,c3});
std::cout << "\n Wanted: " << 1 << " id checks, got: " << c1.getIdChecks() << "\n";
}

那么在现代 C++ 中如何传递可变数量的参数呢?示例表示赞赏!

最佳答案

不幸的是,initializer_list 只能复制它的参数,不能保存对它的引用(至少是直接引用)。但是,有解决方法(示例已修剪):

#include <initializer_list>
#include <iostream>
#include <functional>

//Example class for illustration purposes
class MyClass
{
public:
MyClass() : m_idChecks(0) {}
~MyClass(){}

int getId() const
{
return m_idChecks++;
}
int getIdChecks() const
{
return m_idChecks;
}

private:
mutable int m_idChecks;
};


using r = std::reference_wrapper<MyClass>;
void test_initializerList(std::initializer_list<r> listClasses)
{
// Doing operations on copies of the object:
int sum = 0;
for(const auto& c : listClasses)
{
sum += c.get().getId();
}
}
int main()
{

MyClass c1;
MyClass c2;
MyClass c3;

test_initializerList({c1,c2,c3});
std::cout << "\n Wanted: " << 1 << " id checks, got: " << c1.getIdChecks() << "\n";
}

关于C++ 11通过引用函数传递可变数量的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50211667/

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