Why C++ CLI has no default argument on managed typ

2019-06-15 16:52发布

问题:

The following line has the error Default argument is not allowed.

public ref class SPlayerObj{
private:

    void k(int s = 0){ //ERROR
    }
}

Why C++ has no default argument on managed types ?
I would like to know if there is a way to fix this.

回答1:

It does have optional arguments, they just don't look the same way as the C++ syntax. Optional arguments are a language interop problem. It must be implemented by the language that makes the call, it generates the code that actually uses the default argument. Which is a tricky problem in a language that was designed to make interop easy, like C++/CLI, you of course don't know what language is going to make the call. Or if it even has syntax for optional arguments. The C# language didn't until version 4 for example.

And if the language does support it, how that compiler knows what the default value is. Notable is that VB.NET and C# v4 chose different strategies, VB.NET uses an attribute, C# uses a modopt.

You can use the [DefaultParameterValue] attribute in C++/CLI. But you shouldn't, the outcome is not predictable.



回答2:

In addition to the precise answer from Hans Passant, the answer to the second part on how to fix this, you are able to use multiple methods with the same name to simulate the default argument case.

public ref class SPlayerObj {
  private:
    void k(int s){ // Do something useful...
    }
    void k() { // Call the other with a default value 
       k(0);
    }
}


回答3:

An alternative solution is to use the [OptionalAttribute] along side a Nullable<int> typed parameter. If the parameter is not specified by the caller it will be a nullptr.

void k([OptionalAttribute]Nullable<int>^ s)
{
    if(s == nullptr)
    {
        // s was not provided
    }
    else if(s->HasValue)
    {
        // s was provided and has a value
        int theValue = s->Value;
    }
}
// call with no parameter
k();
// call with a parameter value
k(100);