template <class T>
void MyClass<T>::MyMethod()
{
// ...
// Which of the following initialization is better?
T MyVariable1 = 1; // 1st
T MyVariable2 = 2.0; // 2nd
T MyVariable3 = static_cast<T>(3); // 3rd
// ...
}
Which one is better?
EDIT: T is a primitive type.
If
Tcan only be a primitive type (int,float, etc.), I don’t think there’s any difference; in all cases, the compiler will perform the relevant conversion (and will probably perform the substitution at compile-time).If
Tis a user-defined type, then obviously these won’t compile, unless it has the appropriate constructors defined. At which point, it may make a difference (e.g. if you have bothT::T(int)andT::T(double)defined).