2

So, in C the standard way is stdarg.h. But I'm looking to pull up something a bit like this:

template<int A>
class MyClass {
public:
    MyClass(...) {
        // fill each value of array with an argument.
    };

    virtual ~MyClass() { };
private:
    float array[A];
};

Obviously, the idea is not to have different constructions for every possible amount of arguments. Any suggestions, standard ways, whatsoever?

Thanks,

Julian.

1
  • 1
    Pass a container or use std::initialize_list if you have that. Commented Apr 14, 2012 at 7:50

3 Answers 3

4

In C++11 you can use an std::initializer_list constructor for this kind of scenario. That allows for this type of initialization:

MyClass<5> x{1,2,3,4,5};

although you have to define what happens when the dimensions do not match. But for these kinds of statically sized arrays, it is worth looking at std::array. These have a well defined behaviour when the dimensions of the initializer don't match their own.

Sign up to request clarification or add additional context in comments.

Comments

1

you need to use initializer_list

explicit MyClass(std::initializer_list<T> list_args){
    // fill each value of array with an argument.
};

Comments

0

If you don't have access to C++11 initializer_lists you can just pass a vector.

MyClass(const std::vector& values) {
    //copy values into array
};

MyClass someClass( std::vector<int>(10,4) ); //adds 10x 4 to the vector

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.