I am trying to pass as a function argument a vector of pointers to classes derived from a common base class. The catch is, I wish to do it in a single line, without declarating the vector first and then passing it by reference to the function. I came up with the following solution, which uses a wrapper class to encapsulate each vector element and pass the respective pointer to the vector constructor through an implicit conversion operator.
I am unsure of the consequences of such approach, specifically if, at any point, the classes are being copied multiple times during the vector construction and/or the function call. Could you guys give me a feedback or even a better solution to the problem? Thanks.
class Base
{
public:
};
class Derived1 : public Base
{
public:
Derived1(int number){}
};
class Derived2 : public Base
{
public:
Derived2(const char* string){}
};
template <typename T> class Wrapper
{
private:
T element;
public:
Wrapper<T>(int number):element(number){}
Wrapper<T>(const char* string):element(string){}
operator T* (){return &element;}
};
void Foo(const std::vector<Base*>& list)
{
//DO SOMETHING
}
int main()
{
Foo(std::vector<Base*>({Wrapper<Derived1>(1), Wrapper<Derived2>("name")}));
return 0;
}
std::vector. It would work if you just use the brace-enclosed list directly toFoo.Wrapper<T>(int number)is invalid in c++20. Change it toWrapper(int number)See Is having a declaration Stack<T>(); for the default ctor valid inside a class template. It was a DR so also invalid in c++17.Fooin functionmainis missing a close paren.