0

no type checks on template specializations in c++

When tweaking the code example for template specializations (https://code.sololearn.com/281/#cpp) I came across some very surprising behaviour when using wrong type of argument, like: MyClass<char> ob1(42); MyClass<char> ob2(5.47); No compiler error, no runtime error... I think this is something to think about when using this construct. template < > class MyClass<char> { public: MyClass (char x) { cout <<x<<" is a char!"<<endl; } }; int main () { MyClass<char> ob1(42); MyClass<char> ob2(5.47); MyClass<char> ob3('s'); } output: * is a char!  is a char! s is a char!

13th Dec 2018, 4:16 PM
arjen stolk
arjen stolk - avatar
1 Respuesta
+ 2
Well, a double can be implicitly converted to a char and if you use the specialized version of MyClass for a char then it's quite obvious that the char specialization is going to be used.
13th Dec 2018, 5:24 PM
Dennis
Dennis - avatar