Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get default argument value from a function call c++

Code will probably better explain my problem better than words:

#include <string>

struct Something {};

struct Context
{
    std::string GetUniqueInentifier()
    {
        return "";
    }


    // ERROR
    void Register(const Something& something, const std::string& key = GetUniqueInentifier())
    {

    }
};

int main()
{
    Context c;
    c.Register(Something{}); //<- want to be able to do this 
                                // and a unique identifier will
                                // be automatically assigned 

    c.Register(Something{}, "Some Key"); //<- want to be able to let the user
                                            //  pick an identifier if they want
}

That is clearly not allowed but how can I simulate this behaviour ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t use non-static member functions or variables as a default value to member functions.
Since the value returned by GetUniqueInentifier() doesn’t require an instance of Context, make it static and you can then use it as you tried using it.

static std::string GetUniqueInentifier()
{
    return "";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading