0

How to create a function that can pass a variable number of arguments that are pointers to objects of the same class? It is desirable that it would be impossible to pass other data types. (Its quantity will be passed too)

There are no problems when working with standard types of variables, but no examples of such use could be found.

Wouldn't that be a bad way to use functions?

1 Answer 1

1
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);

Alternatively:

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);

Alternatively:

#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});

Alternatively:

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.