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!
1 Odpowiedź
+ 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.