0

I am trying to initialize a class with a pack passed as an argument to my function. Here is what I got so far:

struct Vec3
{
    float x, y, z;
};

template<typename _Ty, typename... Args>
__forceinline _Ty construct_class(Args&&... arguments)
{
    return _Ty(arguments...);
}

// here I am trying to construct a Vec3 by calling construct_class
Vec3 vec = construct_class<Vec3>(10.f, 20.f, 30.f);

Unfortunately I get the following compiler error in visual studio: C2440 '<function-style-cast>': cannot convert from 'initializer list' to '_Ty'

I have seen people doing this:

template<typename _Ty, typename... Args>
__forceinline _Ty construct_class(Args&&... arguments)
{
    return _Ty(std::forward<Args>(arguments)...);
}

But this also doesn't work for me, I get the exact same compiler error as before.

So my question is how should I use the pack/intializer list inside construct_class to construct the _Ty class (in this case Vec3)? I am not familiar with packs in C++.

SimpleY
  • 68
  • 5
  • 1
    Use brackets: `_Ty{std::forward(arguments)...};` or just `return {std::forward(arguments)...};` – Quimby May 14 '22 at 11:04
  • the tag `pack` doesn't apply here, maybe variadic templates and perfect forwarding – MatG May 14 '22 at 11:07
  • 1
    `_TY` name is reserved to the language implementation. Don't use it as a template parameter. – eerorika May 14 '22 at 11:08
  • 1
    Identifiers starting with `_` followed by an uppercase letter are reserved for the compiler/standard library. `_Ty()` doesn't consider aggregate initialization though, so it fails, since there is no suitable constructor taking the arguments passed. – fabian May 14 '22 at 11:09

1 Answers1

1

You could replace return _Ty(arguments...) with return _Ty{arguments...} as shown below:

//---------------v--------------------- v----->removed the underscore
template<typename Ty, typename... Args>  Ty construct_class(Args&&... arguments)
{
//-----------v------------v------------------->used curly braces instead of parenthesis
    return Ty{arguments...};
}

Working Demo


Also, note that the given program will work with C++20 without having to use curly braces.


Also, What are the rules about using an underscore in a C++ identifier? might come in handy when using leading underscore for names.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • I suggest mentioning that this would work in C++20. – HolyBlackCat May 14 '22 at 11:56
  • @HolyBlackCat Added a note. Though for some reason even with C++20, it doesn't compile [here](https://onlinegdb.com/GHgEhViOs). Maybe there is something wrong with the compiler(or option/flag) they're using. It works as expected [here](https://wandbox.org/permlink/b5f7vmtl3z2hsbA3) though. – Jason May 14 '22 at 12:03