RSS 2.0
Sign In
# Monday, July 20, 2009

Generics in C# look inferior to templates (especially to concepts) in C++, however now and then you can build a wonderful pieces the way a C++ profi would envy.

Consider a generic converter method: T Convert<T>(object value).

In C++ I would create several template specializations for all supported conversions. Well, to make things harder, think of converter provider supporting conversion:

public interface IConverterProvider
{
  Converter<object, T> Get<T>();
}

That begins to be a puzzle in C++, but C# handles it easily!

My first C#'s implementation was too naive, and spent too many cycles in provider, resolving which converter to use. So, I went on, and have created a sofisticated implementation like this:

  private IConverterProvider provider = ...

  public T Convert<T>(object value)
  {
    var converter = provider.Get<T>();

    return converter(value);
  }

...

public class ConverterProvider: IConverterProvider
{
  public Converter<object, T> Get<T>()
  {
    return Impl<T>.converter;
  }

  private static class Impl<T>
  {
    static Impl()
    {
      // Heavy implementation initializing converters.
      converter = ...
    }

    public static readonly Converter<object, T> converter;
  }
}

Go, and do something close in C++!

Monday, July 20, 2009 7:18:51 AM UTC  #    Comments [0] -
Tips and tricks
All comments require the approval of the site owner before being displayed.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview
Archive
<October 2024>
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789
Statistics
Total Posts: 387
This Year: 3
This Month: 0
This Week: 0
Comments: 1624
Locations of visitors to this page
Disclaimer
The opinions expressed herein are our own personal opinions and do not represent our employer's view in anyway.

© 2024, Nesterovsky bros
All Content © 2024, Nesterovsky bros
DasBlog theme 'Business' created by Christoph De Baene (delarou)