简体   繁体   中英

C# Generic behavior with C++ Templates

I'm attempting to port some C# code to C++. I'd like to keep the structure similar, but I realize this might not always be possible.

Based on my research, C++ templates are supposed to be more powerful/flexible than C# Generics, yet I can't seem to recreate a particular behavior.

Here's an overly simplified example of my current C# structure:

public class MyGeneric<T>
{
    public void MyTypeSafeMethod(T arg1)
    {
        //logic here
    }
}

public class MyImplA : MyGeneric<MyImplA>
{
    //Class config etc..
}

public class MyImplB : MyGeneric<MyImplB>
{
    //Other config etc...
}

public static class MyCollectionOfGenericImpl
{
    public static MyImplA A = new MyImplA();
    public static MyImplB B = new MyImplB();
}

public class Program
{
    void Main()
    {
        //Doesn't compile, method is typesafe 
        MyCollectionOfGenericImpl.A.MyTypeSafeMethod(MyCollectionOfGenericImpl.B);
    }
}

As of right now, I don't really see a way to do this using the C++ templates (did some looking at typedef + templates, but I don't see how that will work for me).

Currently, my solution would be to scrap templates completely. I would have a base class (ie MyGeneric) with a protected method (ie MyTypeSafeMethodProt) that has my logic. I would then expose a new type-safe method in each class implementation that utilizes the protected logic.

Any way to achieve this with templates or another way with less code?

There is no problem at all converting the given code to C++. It is just a syntactical (mechanical) transformation. This reproduces the desired compilation error on the call in the main function.

In short, I'm completely baffled as to what the perceived problem is.

But in the hope that it may help, regardless of problem, here's corresponding C++ code with the original C# code's names:

template< class T >
struct MyGeneric
{
    void MyTypeSafeMethod( T& arg1 )
    {
        //logic here
    }
};

struct MyImplA : MyGeneric<MyImplA>
{
    //Class config etc..
};

struct MyImplB : MyGeneric<MyImplB>
{
    //Other config etc...
};

struct MyCollectionOfGenericImpl
{
    static MyImplA A;
    static MyImplB B;
};

MyImplA MyCollectionOfGenericImpl::A;
MyImplB MyCollectionOfGenericImpl::B;

auto main()
    -> int
{
    //Doesn't compile, method is typesafe 
    MyCollectionOfGenericImpl::A.MyTypeSafeMethod( MyCollectionOfGenericImpl::B );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM