How do I initialize template type variables?
-
21-03-2021 - |
Question
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.
Solution
If T
can 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 T
is 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 both T::T(int)
and T::T(double)
defined).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow