• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
swiftcoder

SFINAE equivalent in C#?

16 posts in this topic

I've just started mucking with C# generics, and it seems that I'm running headlong into their limitations. In C++ I can do something like this:
[code]template <typename T>
void Write(T data) {
int size = T.SizeInBytes;
// ...
}[/code]
And I can call Write() with any type that contains an integer-compatible member variable named 'SizeInBytes'. If one tries to do the same in C#:
[code]public void Write<T>(T data) where T : struct {
int size = T.SizeInBytes;
// ...
}[/code]
Then it errors out with "error CS0119: Expression denotes a `type parameter', where a `variable', `value' or `type' was expected". Quite reasonably, since C# doesn't allow the use of expressions with generic types which can't be applied solely given the constraints.

Are there any common idioms to working around this? Assuming that (a) I need to work with value types, and (b) these structs are defined in a 3rd party library (i.e. I can't modify the definition of the struct itself).
1

Share this post


Link to post
Share on other sites
I believe Marshal.SizeOf and the typeof() operator should do what you need, it's been a while since I've used it though and I'm not sat in front of a computer I can test this on, but hopefully the following should work.

[CODE]
int size = Marshal.SizeOf(typeof(T));
[/CODE] Edited by adt7
2

Share this post


Link to post
Share on other sites
I've had similar problems a few times, usually it ends up as an unholy mess of generics and reflection.
1

Share this post


Link to post
Share on other sites
[quote name='wack' timestamp='1348867634' post='4984870']
I've had similar problems a few times, usually it ends up as an unholy mess of generics and reflection.[/quote]
Ja, I'm quickly starting to miss C++ templates.

I'm going to have to unlearn my template-centric coding style for C#.
0

Share this post


Link to post
Share on other sites
[quote name='swiftcoder' timestamp='1348869994' post='4984880']
Ja, I'm quickly starting to miss C++ templates.

I'm going to have to unlearn my template-centric coding style for C#.
[/quote]
There's a number of aspects of C++ templates that bug me. Stuff like this in particular:
[source lang="cpp"]void function(const std::vector&lt;Objects*&gt;&){}
void constFunction(const std::vector&lt;const Objects*&gt;&){}

std::vector&lt;Objects*&gt; objectList;
function(objectList);
constFunction(objectList); // compile error[/source]

Do C# generics let you do that sort of stuff easily?
0

Share this post


Link to post
Share on other sites
[quote name='Slavik81' timestamp='1348878723' post='4984910']
[quote name='swiftcoder' timestamp='1348869994' post='4984880']
Ja, I'm quickly starting to miss C++ templates.

I'm going to have to unlearn my template-centric coding style for C#.
[/quote]
There's a number of aspects of C++ templates that bug me. Stuff like this in particular:
[source lang="cpp"]void function(const std::vector&lt;Objects*&gt;&){}
void constFunction(const std::vector&lt;const Objects*&gt;&){}

std::vector&lt;Objects*&gt; objectList;
function(objectList);
constFunction(objectList); // compile error[/source]

Do C# generics let you do that sort of stuff easily?
[/quote]

There is no such thing as "const" in C#, so that's a non issue.
However, it's normal that it doesn't work in c++. An array of const objects is not all all the same type as an array of non const objects. You can't expect implicit conversion of those two types. If you want to guarantee what I suspect is your wanted behavior, you should use a container where the element access function/operator returns const member if the container is const:

[source lang="cpp"]object* array &lt object* &gt ::operator[](int i);
const object* array &lt object* &gt ::operator[](int i) const;[/source]
with those two functions:
[source lang="cpp"]void function(array &lt objects* &gt &){}
void constFunction(const array &lt objects* &gt &){}[/source]
0

Share this post


Link to post
Share on other sites
The relatively coarse-grained nature of generic constraints in C# / the CLI is my biggest annoyance with the platform. There's really no reason why the compiler couldn't infer method (and operator!) and property level constraints and simply require that all type arguments provide them.
1

Share this post


Link to post
Share on other sites
[quote name='BenMatlock' timestamp='1348879548' post='4984913']
There is no such thing as "const" in C#, so that's a non issue.
However, it's normal that it doesn't work in c++. An array of const objects is not all all the same type as an array of non const objects. You can't expect implicit conversion of those two types.[/quote]
I could expect it, given that the two objects should have both identical code and data, and one has an interface that is a subset of the other. The fact that it's so difficult to use one in place of the other is just a limitation imposed by poor design choices in the C++ template system.

If it C++ disallowed atrocities like this, the types would be compatible:
[code]struct MyObject{};

template<class T> struct MyTemplateClass {
T x;
};

template<> struct MyTemplateClass<const MyObject*>{};

int main()
{
MyObject obj;

MyTemplateClass<MyObject*> i1;
i1.x= &obj;

MyTemplateClass<const MyObject*> i2;
i2.x= &obj; // compile error
}[/code]

Reading through stuff about C# generics, it seems that they maintain restrictions to prevent that sort of thing.
0

Share this post


Link to post
Share on other sites
[quote name='Mike.Popoloski' timestamp='1348882742' post='4984924']
The relatively coarse-grained nature of generic constraints in C# / the CLI is my biggest annoyance with the platform. There's really no reason why the compiler couldn't infer method (and operator!) and property level constraints and simply require that all type arguments provide them.
[/quote]

As far as I can tell, the reason C# generics have the limitations they do is because they can be deployed in DLLs. This means that the compiled generic must work both for existing 'T' as well as unknown types that someone may cook up in the future (as long as those types fulfill all of the constraints the generic specifies). The compiler ensures that the generic can be used by anything that supports those constraints, without needing to actually be instantiated like C++ templates.

This is both their greatest strength and the cause of all of their weaknesses.
2

Share this post


Link to post
Share on other sites
One must also keep in mind that generics are not at all equivalent to C++ templates or even Java generics (type erasure!). Some of the major annoyances with the platform have just recently (.NET 4) been fixed (like co- and contravariance issues with generic collections and enumerations).
1

Share this post


Link to post
Share on other sites
[quote name='Slavik81' timestamp='1348884726' post='4984931']
I could expect it, given that the two objects should have both identical code and data, and one has an interface that is a subset of the other. The fact that it's so difficult to use one in place of the other is just a limitation imposed by poor design choices in the C++ template system.
[/quote]

Actually it is the result of a powerful C++ design choice: template specializations.

[quote name='Slavik81' timestamp='1348884726' post='4984931']
If it C++ disallowed atrocities like this, the types would be compatible:
[CODE]
struct MyObject{};
template struct MyTemplateClass {
T x;
};
template<> struct MyTemplateClass<const MyObject*>{};
int main()
{
MyObject obj;

MyTemplateClass<MyObject*> i1;
i1.x= &obj;

MyTemplateClass<const MyObject*> i2;
i2.x= &obj; // compile error
}
[/code]
[/quote]

It seems it would be a pretty silly tradeoff to disallow template specializations in order to allow implicit template type conversions, particularly when the solution to your original problem is so simple:

[CODE]
template<typename ContainerT>
void function(const ContainerT&){}
[/CODE] Edited by krippy2k8
1

Share this post


Link to post
Share on other sites
[quote name='krippy2k8' timestamp='1348996241' post='4985300']It seems it would be a pretty silly tradeoff to disallow template specializations in order to allow implicit template type conversions, particularly when the solution to your original problem is so simple:

[CODE]
template<typename ContainerT>
void function(const ContainerT&){}
[/CODE]
[/quote]
That would be a reasonable solution if it did not have such a dramatic impact on compilation time, and if it did not require major workarounds to apply to virtual functions.

There are definite advantages to the restrictions C# imposes on its generics. Edited by Slavik81
0

Share this post


Link to post
Share on other sites
[quote name='Slavik81' timestamp='1349110169' post='4985793']
That would be a reasonable solution if it did not have such a dramatic impact on compilation time, and if it did not require major workarounds to apply to virtual functions.

There are definite advantages to the restrictions C# imposes on its generics.
[/quote]

That should have little impact on compile times. Certainly not "dramatic."

And yes, there are definite advantages to the restrictions C# imposes on it's generics. There are also definite disadvantages. A major design focus behind C# is in fact compile times and convenience, whereas C++ focuses more on flexibility and run-time performance. Template specialization is a big part of that. It's certainly not a design flaw. And the workarounds you're talking about in regards to virtual functions are typically only necessary if you use questionable design choices in your own code from the perspective of C++, with modern C++ absolutely favoring generics and generic algorithms over inheritance and virtual functions, especially when it comes to operating on template types. Edited by krippy2k8
0

Share this post


Link to post
Share on other sites
[quote name='Nypyren' timestamp='1348885299' post='4984933']
[quote name='Mike.Popoloski' timestamp='1348882742' post='4984924']
The relatively coarse-grained nature of generic constraints in C# / the CLI is my biggest annoyance with the platform. There's really no reason why the compiler couldn't infer method (and operator!) and property level constraints and simply require that all type arguments provide them.
[/quote]

As far as I can tell, the reason C# generics have the limitations they do is because they can be deployed in DLLs. This means that the compiled generic must work both for existing 'T' as well as unknown types that someone may cook up in the future (as long as those types fulfill all of the constraints the generic specifies). The compiler ensures that the generic can be used by anything that supports those constraints, without needing to actually be instantiated like C++ templates.

This is both their greatest strength and the cause of all of their weaknesses.
[/quote]Though there is another potential design decision that would enable this, which would be to allow interface implementation to be implicit. For example, if you're like me and wanted to write a generic structure that does math of some kind [for example, a vector class], it'd be nice if all you had to do was specify that said object implemented an interface that exposed an add, multiply, divide, and a negate function. The compiler can infer the existence of an interface that has these properties simply enough [or maybe even demand that you implement the interface to make it additionally explicit]. The missing link is to be able to take a type, notice that it has an add, multiply, divide, and a negate function, and deduce that it implicity satisfies that interface.

In fact, the lack of this, and the lack of explicit extension-method style fitting an existing type into a new interface, is what really prevents things like generic matrix classes. This is entirely do-able though, and is something you can wedge into a DLL without much issue.
0

Share this post


Link to post
Share on other sites
[quote name='Oolala' timestamp='1349462222' post='4987203']
Though there is another potential design decision that would enable this, which would be to allow interface implementation to be implicit.[/quote]

C# and .Net 4.0 have their own implementation which allows this. It's called 'dynamic typing'.

Anonymous interfaces (one interface per member signature for every type) would be bad, because it would allow unintentional access of that interface, which would lead to bugs.

It would also hinder someone from learning your codebase. Anyone working on a large team will tell you that the bulk of their job isn't writing new code, it's learning what everyone else's code does. The more things in a language that are left unstated, the easier it is for someone to overlook some hidden behavior of the code. Edited by Nypyren
0

Share this post


Link to post
Share on other sites
[quote name='Nypyren' timestamp='1349465771' post='4987222']
[quote name='Oolala' timestamp='1349462222' post='4987203']
Though there is another potential design decision that would enable this, which would be to allow interface implementation to be implicit.[/quote]
C# and .Net 4.0 have their own implementation which allows this. It's called 'dynamic typing'.[/quote]
And everyone else calls it 'structural sub-typing' (aka 'duck typing'). Which C++ templates support statically, and languages like Python support dynamically.

[quote]It would also hinder someone from learning your codebase. Anyone working on a large team will tell you that the bulk of their job isn't writing new code, it's learning what everyone else's code does. The more things in a language that are left unstated, the easier it is for someone to overlook some hidden behavior of the code.[/quote]
While both of the implementations above present significant barriers to code readability, I'm not sure that the structural sub-typing is to blame. I'm pretty sure this is a feature that can be done simply and well, given sufficient forethought.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0