Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there something similar to this C++ template?

template <int A>
class B
{
    int f()
    {
        return A;
    }
}

I want to make every instance of B<1>, B<2>, etc (eg tuple) a different type.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
245 views
Welcome To Ask or Share your Answers For Others

1 Answer

The short answer is no.

It doesn't fit the way C# generics, as apposed to C++ templates, work.

The .net generics are not a language feature, they are a runtime feature. The runtime knows how to instantiate generics from special generic bytecode which is rather restricted compared to what C++ templates can describe.

Compare this with C++ templates, which basically instantiate the whole AST of the class using substituted types. It'd be possible to add AST based instantiation to the runtime, but it'd certainly be much more complex than the current generics.

Without features like value-type arrays (which only exist in unsafe code), recursive template instantiation or template specialization using such parameters wouldn't be very useful either.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...