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++.

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

1 Answer 1

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.

2
  • I suggest mentioning that this would work in C++20. May 14, 2022 at 11:56
  • @HolyBlackCat Added a note. Though for some reason even with C++20, it doesn't compile here. Maybe there is something wrong with the compiler(or option/flag) they're using. It works as expected here though. May 14, 2022 at 12:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.