简体   繁体   中英

Calling non default template constructor in a Class constructor

Is it possible in the following example to call the "not default constructor" of class A for every element of mVector within the constructor of class B ?

class A {
public:
    A (int n) {/*stuff*/}
};

class B {
public:
    B (): mVector(10) {}  //call A(int n) constructor?

private:
    vector<A> mVector;
};

If you want to set all the elements to the same value, there's a constructor for that

mVector(10, 42)  // 10 elements initialised with value 42

If you want to set the elements to different values, use list initialisation

mVector{1,2,3,4,5,6,7,8,9,10}  // 10 elements with different values

Strictly speaking, this doesn't do exactly what you describe; it creates a temporary T , and then uses that to copy-initialise each vector element. The effect should be the same, unless your type has weird copy semantics.

You could do one thing here:-

B() : mVector(10, A(10))
{
}

Or

B() : mVector(10, 10)
{
}

Both are essentially the same thing. However, former one is more efficient.

You can use the constructor overload of std::vector taking an element count and a value which for your use case is equivalent to:

std::vector(size_type count, const T& value);

Use it to initialize the elements with the value type's non default constructor:

std::vector<A> mVector(10, A{0}); // 10 elements copy initialized using 'A{0}'.

Or when initializing in the initialization list:

B() : mVector(10, A{0}) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM