【发布时间】:2021-05-29 11:43:33
【问题描述】:
如何创建一个可以传递可变数量参数的函数,这些参数是指向同一类对象的指针?希望不可能传递其他数据类型。 (它的数量也会被传递)
使用标准类型的变量时没有问题,但找不到这种使用的例子。
这不是使用函数的坏方法吗?
【问题讨论】:
标签: c++ function class arguments
如何创建一个可以传递可变数量参数的函数,这些参数是指向同一类对象的指针?希望不可能传递其他数据类型。 (它的数量也会被传递)
使用标准类型的变量时没有问题,但找不到这种使用的例子。
这不是使用函数的坏方法吗?
【问题讨论】:
标签: c++ function class arguments
class C
{
public:
void DoSomething(int n, C* ptrs[]) {
// do something with n number of pointers from ptrs array...
}
};
C c1, c2, c3, c4;
C* arr[] = {&c2, &c3, &c4};
c1.DoSomething(3, arr);
或者:
class C
{
public:
template<size_t n>
void DoSomething(C* (&ptrs)[n]) {
// do something with n number of pointers from ptrs array...
}
};
C c1, c2, c3, c4;
C* arr[] = {&c2, &c3, &c4};
c1.DoSomething(arr);
或者:
#include <initializer_list>
class C
{
public:
void DoSomething(std::initializer_list<C*> ptrs) {
// do something with ptrs...
}
};
C c1, c2, c3, c4;
c1.DoSomething({&c2, &c3, &c4});
或者:
class C
{
public:
void DoSomething() {}
template<typename ...Ts>
void DoSomething(C* c, Ts... args) {
// do something with c...
DoSomething(args...);
}
};
C c1, c2, c3, c4;
c1.DoSomething(&c2, &c3, &c4);
【讨论】: