Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


SFINAE equivalent in C#?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
16 replies to this topic

#1 swiftcoder   Senior Moderators   -  Reputation: 10361

Like
1Likes
Like

Posted 28 September 2012 - 06:02 AM

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:
template <typename T>
void Write(T data) {
     int size = T.SizeInBytes;
     // ...
}
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#:
public void Write<T>(T data) where T : struct {
     int size = T.SizeInBytes;
     // ...
}
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).

Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]


Sponsor:

#2 adt7   Members   -  Reputation: 434

Like
2Likes
Like

Posted 28 September 2012 - 06:16 AM

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.

int size = Marshal.SizeOf(typeof(T));

Edited by adt7, 28 September 2012 - 06:17 AM.


#3 swiftcoder   Senior Moderators   -  Reputation: 10361

Like
0Likes
Like

Posted 28 September 2012 - 06:34 AM

Beautiful, thanks!

Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]


#4 wack   Members   -  Reputation: 1345

Like
1Likes
Like

Posted 28 September 2012 - 03:27 PM

I've had similar problems a few times, usually it ends up as an unholy mess of generics and reflection.

#5 swiftcoder   Senior Moderators   -  Reputation: 10361

Like
0Likes
Like

Posted 28 September 2012 - 04:06 PM

I've had similar problems a few times, usually it ends up as an unholy mess of generics and reflection.

Ja, I'm quickly starting to miss C++ templates.

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

Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]


#6 Slavik81   Members   -  Reputation: 360

Like
0Likes
Like

Posted 28 September 2012 - 06:32 PM

Ja, I'm quickly starting to miss C++ templates.

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

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?

#7 BenMatlock   Members   -  Reputation: 137

Like
0Likes
Like

Posted 28 September 2012 - 06:45 PM


Ja, I'm quickly starting to miss C++ templates.

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

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?


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]

#8 Mike.Popoloski   Crossbones+   -  Reputation: 2931

Like
1Likes
Like

Posted 28 September 2012 - 07:39 PM

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.
Mike Popoloski | Journal | SlimDX

#9 Slavik81   Members   -  Reputation: 360

Like
0Likes
Like

Posted 28 September 2012 - 08:12 PM

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.

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:
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
}

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

#10 Nypyren   Crossbones+   -  Reputation: 4782

Like
2Likes
Like

Posted 28 September 2012 - 08:21 PM

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.


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.

#11 darookie   Members   -  Reputation: 1437

Like
1Likes
Like

Posted 29 September 2012 - 12:54 AM

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).

#12 krippy2k8   Members   -  Reputation: 646

Like
1Likes
Like

Posted 30 September 2012 - 03:10 AM

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.


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

If it C++ disallowed atrocities like this, the types would be compatible:

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
}


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:

template<typename ContainerT>
void function(const ContainerT&){}

Edited by krippy2k8, 30 September 2012 - 03:38 AM.


#13 Slavik81   Members   -  Reputation: 360

Like
0Likes
Like

Posted 01 October 2012 - 10:49 AM

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:

template<typename ContainerT>
void function(const ContainerT&){}

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, 01 October 2012 - 11:23 AM.


#14 krippy2k8   Members   -  Reputation: 646

Like
0Likes
Like

Posted 05 October 2012 - 02:50 AM

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.


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, 05 October 2012 - 02:56 AM.


#15 Oolala   Members   -  Reputation: 853

Like
0Likes
Like

Posted 05 October 2012 - 12:37 PM


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.


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.

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.

#16 Nypyren   Crossbones+   -  Reputation: 4782

Like
0Likes
Like

Posted 05 October 2012 - 01:36 PM

Though there is another potential design decision that would enable this, which would be to allow interface implementation to be implicit.


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, 05 October 2012 - 01:44 PM.


#17 swiftcoder   Senior Moderators   -  Reputation: 10361

Like
0Likes
Like

Posted 05 October 2012 - 02:18 PM


Though there is another potential design decision that would enable this, which would be to allow interface implementation to be implicit.

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

And everyone else calls it 'structural sub-typing' (aka 'duck typing'). Which C++ templates support statically, and languages like Python support dynamically.

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.

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.

Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS