Home > Net >  Is there a way to get or notice the default arguments of the function?
Is there a way to get or notice the default arguments of the function?

Time:06-14

Example I have a lots of class, each have it own constructor with defaut arguments, and each have a fake_constructor function which have same arguments as the constructor so I can take the function pointer from it.

class someRandomClass
{
public:
    someRandomClass(int a = 0, float b = 0.f, double c = 0.0, const char* d = "") {}

    void fake_constructor(int a = 0, float b = 0.f, double c = 0.0, const char* d = "") {}
};

And I have a function which take a class type and construct it with the parameter pack args:

template<typename Cls, typename... T>
void callClassConstructor(T... args)
{
    // check if the arguments is same as class contructor.
    if (compareAugments(&Cls::fake_constructor, args...) == true)
        Cls(args...);  // construct the class.
}

Also, I have a function to compare if the parameter pack are same as the class contructor arguments:

template<typename type, typename Cls, typename...Arg1, typename...Arg2>
bool compare_Class_Augments(type(Cls::* func)(Arg1...), Arg2...args)
{
    return (std::is_same_v<std::tuple<Arg1...>, std::tuple<Arg2...>>);
}

This's how it work: first I call the callClassConstructor and pass to it the class type, and the arguments, then it will get the fake_constructor which same as the constructor and compare its arguments with the arguments I give, if it are same then it will contruct that class type with that argument.

int main()
{
    callClassConstructor<someRandomClass>(69, 5.f, 1.23, "hello");
}

But, It only work if I pass full the arguments, if I do this:

callClassConstructor<someRandomClass>(69, 5.f);

It won't work, cause it don't understand the default arguments , it only check if the arguments type are same:

Example:
int, float, double, const char*
int, float

Sorry for this stupid question, and the Explain not clearly. PS: I know I can just remove the default arguments part and pass full the arguments, but I want to know if there's a way to solve this.

CodePudding user response:

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)...);
        // ....
    }
}
  • Related