c++ - Why is type checking inside templates more strict? -
this question has answer here:
- implicit conversion int shared_ptr 3 answers
i reading effective modern c++ s. meyers, , found can't quite wrap head around.
item 8 explains why nullptr should preferred on 0 or null. main argument in favor of nullptr safer behavior in overload resolutions. in practice avoid unintended mixups between pointers , integer types, not point of question.
to actual question, consider code below, based on example used in book:
#include <memory> class myclass { int a; }; // dummy functions take pointer types int f1(std::shared_ptr<myclass> spw){return 1;}; double f2(std::unique_ptr<myclass> upw){return 1.0;}; bool f3(myclass* pw){return true;}; // template calls function pointer argument template<typename functype, typename ptrtype> auto callfun(functype func, ptrtype ptr) -> decltype(func(ptr)) { return func(ptr); } int main() { // passing null ptr in 3 different ways // work fine int case auto result1 = f1(0); // pass 0 null ptr f1 auto result2 = f2(null); // pass null null ptr f2 auto result3 = f3(nullptr); // pass nullptr null ptr f3 } // passing null ptr in 3 different ways through template // nullptr works in case auto result4 = callfun(f1, 0); // compile error! auto result5 = callfun(f2, null); // compile error! auto result6 = callfun(f3, nullptr); // ok return 0; } the first 3 direct calls f1, f2 , f3 compile fine either 0, null, or nullptr null pointer. subsequent 3 calls, performed through templates function callfun more picky: have use nullptr, or no conversion between integer types (0 , null) accepted. in other words type checking seems more strict when occurs inside template. can clarify going on?
callfun deduces type of ptrtype 0 , null int, don't implicitly convert pointer type.
if want see mean, try storing 0 , null in auto'd variable first, , calling f1 f2 variables. won't compile.
0 , null implicitly cast pointer type because they're literal values guess. there's in standard think point.
Comments
Post a Comment