RSS 2.0
Sign In
# Monday, 20 July 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, 20 July 2009 07:18:51 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
<2024 November>
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567
Statistics
Total Posts: 387
This Year: 3
This Month: 0
This Week: 0
Comments: 1900
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)