Doing an experiment of translating .NET IL to C++ in a human readable fashion.
Here is the issue: C# allows you to resolve multiple interfaces with the same method name that only differ in return type. C++ doesn't seem to support this however making resolving two interfaces impossible using the vTable (or am i wrong?).
I've found a way to replicate the C# approach in C++ using templates but am wondering if there is a way that doesn't require templates that solves the same issue? Templates are verbose and I'd prefer not using them for every interface type if possible.
Here is the C++ version.
template<typename T>
class IMyInterface
{
public: short (T::*Foo_IMyInterface)() = 0;
};
template<typename T>
class IMyInterface2
{
public: int (T::*Foo_IMyInterface2)() = 0;
};
class MyClass : public IMyInterface<MyClass>, public IMyInterface2<MyClass>
{
public: MyClass()
{
Foo_IMyInterface = &MyClass::Foo;
Foo_IMyInterface2 = &MyClass::IMyInterface2_Foo;
}
public: virtual short Foo()
{
return 1;
}
private: int IMyInterface2_Foo()
{
return 1;
}
};
class MyClass2 : public MyClass
{
public: virtual short Foo() override
{
return 2;
}
};
void InvokeFoo(IMyInterface<MyClass>* k)
{
(((MyClass*)k)->*k->Foo_IMyInterface)();
}
void main()
{
auto a = new MyClass2();
InvokeFoo(a);
}
Here is the C# reference source the C++ one is based on.
interface IMyInterface
{
short Foo();
}
interface IMyInterface2
{
int Foo();
}
class MyClass : IMyInterface, IMyInterface2
{
public virtual short Foo()
{
return 1;
}
int IMyInterface2.Foo()
{
return 1;
}
}
class MyClass2 : MyClass
{
public override short Foo()
{
return 2;
}
}
namespace CSTest
{
class Program
{
static void InvokeFoo(IMyInterface k)
{
k.Foo();
}
static void Main(string[] args)
{
var a = new MyClass2();
InvokeFoo(a);
}
}
}
This C++ method doesn't work below but wish it did (its more what I'm going for).
class IMyInterface
{
public: virtual short Foo() = 0;
};
class IMyInterface2
{
public: virtual int Foo() = 0;
};
class MyClass : public IMyInterface, public IMyInterface2
{
public: virtual short Foo()
{
return 1;
}
private: int IMyInterface2::Foo()// compiler error
{
return 1;
}
};
class MyClass2 : public MyClass
{
public: virtual short Foo() override
{
return 2;
}
};
void InvokeFoo(IMyInterface* k)
{
k->Foo();
}
void main()
{
auto a = new MyClass2();
InvokeFoo(a);
}