c++ - 为什么模板内部的类型检查更严格?

标签 c++ templates c++11 types overloading

<分区>

我正在阅读 S. Meyers 的 Effective Modern C++,我发现了一些我无法完全理解的东西。

条款 8 解释了为什么 nullptr 应该优先于 0NULL。支持 nullptr 的主要论据是重载决议中的更安全行为。在实践中,您可以避免指针和整数类型之间的意外混淆,但这不是我的问题的重点。

要回答我的实际问题,请考虑以下代码,该代码基于书中使用的示例:

#include <memory>

class MyClass {
    int a;
};

// dummy functions that 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 that calls a function with a 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 three different ways
    // they all work fine int this case
    auto result1 = f1(0);        // pass 0 as null ptr to f1
    auto result2 = f2(NULL);     // pass NULL as null ptr to f2
    auto result3 = f3(nullptr);  // pass nullptr as null ptr to f3 }

    // passing null ptr in three different ways through the template
    // only nullptr works in this case
    auto result4 = CallFun(f1, 0);         // compile error!
    auto result5 = CallFun(f2, NULL);      // compile error!
    auto result6 = CallFun(f3, nullptr);   // OK

    return 0;
}

f1f2f3 的前三个直接调用对于 0 编译都很好>NULLnullptr 作为空指针。通过模板函数 CallFun 执行的后续 3 次调用更加挑剔:您必须使用 nullptr,或者不进行整数类型之间的转换 (0NULL) 将被接受。换句话说,当类型检查发生在模板内部时,它似乎更加严格。有人可以澄清发生了什么吗?

最佳答案

CallFun推导出 PtrType 的类型对于 0NULL作为int ,它不会隐式转换为指针类型。

如果您想明白我的意思,只需尝试存储 0NULLauto 'd 变量,然后调用 f1一个f2从那些变量。他们不会编译。

0NULL它们本身隐式转换为指针类型,因为我猜它们是文字值。标准中可能有一些关于它的内容,但我想你明白了。

关于c++ - 为什么模板内部的类型检查更严格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30237184/

相关文章:

c++ - 如何区分构造函数

c++ - 不允许使用非成员函数重载 C++ 转换运算符的理由是什么

c++ - 为什么在sfml中加载字体时出错

c++ - 通过引用返回已销毁的局部变量的成员

Django:同名的嵌套内容 block

c++ - VS2013 : STL regex class crashes when regular expression contains\

C++11:std::vector::shrink_to_fit 复杂度

c++ - 实现嵌套在模板类中的类的成员函数

c# - 使用 C++ 创建 Windows Phone 8 GUI

c++ - 转换为指向模板的指针是否会实例化该模板?