If I remember correctly, C++ templates are only evaluated when you actually try to use them. So you could have code in a template that can't compile, but you will only know about it if you try to use the template somewhere. I'm not saying this is a good thing, but it does have advantages from what I am seeing right now with how C# generics work.
Say I have this:
void Foo(float[] buffer)
{
// Process buffer
}
void Foo(double[] buffer)
{
// Process buffer
}
void Bar<T>(T[] buffer)
{
//...
Foo(buffer);
//...
}That does not compile with error:
Argument 1: cannot convert from 'T[]' to 'float[]
The error is understandable, since T is not constrained to only float or double, and there is no way that I know of to constrain it only to float or double. You can constrain it to struct, but that doesn't help. It would have been helpful if the compiler took into account how you called Bar and only give an error if you try to call with a type that it can't ultimately resolve (like what would happen in the case of a C++ template).
The point is that it is extremely easy for us to see what should work and what should not work (only float or double would work) , so why can't the compiler be a little bit smarter and figure this out too? Seems it would be really helpful in some cases.
Or is there another way to refactor this code so that it does work? Obviously this example is very simple, but in my code, Bar is quite complex and I don't want to rewrite the same method multiple times for each type of buffer I am going to support. Yes inside Bar I can check the types manually (if T is float) and cast to each type when calling Foo but it doesn't seem very elegant.
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.