Search code examples
c++classparametersargumentsc++17

Construct a class that have default arguments with given arguments


Example I have some random class, which constructor have some default arguments. And I have a function to construct there class with some given arguments, and I need somehow to check if I can construct there class with those given arguments

class someRandomClass
{
public:
    someRandomClass(int a = 0, float b = 0.f, double c = 0.0, const char* d = "") {}
    // any argument you can think of
};

template<typename Cls, typename... Ts>
void constructClass(Ts... args) {
    // something to check
    if (constructable(Cls, Ts...))
        Cls myClass(args...);
}

Are there some way to achieve this?


Solution

  • std::is_constructible traits might help (And you might get rid of fake_constructor :-) ):

    template<typename Cls, typename... Ts>
    // requires(std::is_constructible_v<Cls, Ts&&...>) // C++20,
                                                      // or SFINAE for previous version
    void callClassConstructor(Ts&&... args)
    {
        if constexpr (std::is_constructible_v<Cls, Ts&&...>)
        {
            Cls myClass(std::foward<Ts>(args)...);
            // ....
        }
    }