I've a C# class library with overloaded methods, and one method has a ref parameter and the other has a value parameter. I can call these methods in C#, but I can't get it right in C++/CLI. It's seems compiler can't distinguish these two methods.
Here is my C# code
namespace test {
public class test {
public static void foo(int i)
{
i++;
}
public static void foo(ref int i)
{
i++;
}
}
}
and my C++/CLI code
int main(array<System::String ^> ^args)
{
int i=0;
test::test::foo(i); //error C2668: ambiguous call to overloaded function
test::test::foo(%i); //error C3071: operator '%' can only be applied to an instance of a ref class or a value-type
int %r=i;
test::test::foo(r); //error C2668: ambiguous call to overloaded function
Console::WriteLine(i);
return 0;
}
I know in C++ I can't declare overload functions where the only difference in the function signature is that one takes an object and another takes reference to an object, but in C# I can.
Is this a feature supported in C# but not in C++/CLI? Is there any workaround?
The function call operator () can be overloaded for objects of class type. When you overload ( ), you are not creating a new way to call a function. Rather, you are creating an operator function that can be passed an arbitrary number of parameters.
Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures. This feature is present in most of the Object Oriented Languages such as C++ and Java.
C does not support operator overloading (beyond what it built into the language).
C++ adds a few of its own operators, most of which can be overloaded except :: and . * .
As a workaround you could build a C# helper class that you use in C++/CLI
namespace test
{
public class testHelper
{
public static void fooByVal(int i)
{
test.foo(i);
}
public static void fooByRef(ref int i)
{
test.foo(ref i);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With