c++ - 为什么 VC++ 允许没有完整模板参数的模板类实例?

标签 c++ templates visual-c++ c++11 unique-ptr

在VC++ 2013的C++头文件memory中,我发现类unique_ptr定义如下:

template<class _Ty, class _Dx> // = default_delete<_Ty>
class unique_ptr
{
    ...
};

让我感到困惑的是:模板参数没有默认类型,这是 C++11 标准所要求的。 (参见 here)

但是,我可以在没有任何警告或错误的情况下编译以下代码:

#include <memory>

using namespace std;

int main()
{
    unique_ptr<int>(new int); // Should be OK! ???
    // rather than unique_ptr<int, default_delete<int>>(new int);
}

为什么?

最佳答案

默认参数在前面的前向声明中指定:

// [memory:24]
_STD_BEGIN
 #if _HAS_CPP0X
template<class _Ty>
    struct default_delete;

template<class _Ty,
    class _Dx = default_delete<_Ty> >
    class unique_ptr;
 #endif /* _HAS_CPP0X */

 // [...]
 // [memory:1276]
// TEMPLATE CLASS unique_ptr SCALAR
template<class _Ty,
    class _Dx>  // = default_delete<_Ty>
    class unique_ptr
        : private _Unique_ptr_base<_Ty, _Dx,
            is_empty<_Dx>::value
                || is_same<default_delete<_Ty>, _Dx>::value>
    {   // non-copyable pointer to an object

这是有效的,就像在函数定义之前为函数声明默认参数一样有效,例如

void foo(int x = 5);
void foo(int x) { /* ... */ }

[C++11: 14.1/10]: The set of default template-arguments available for use with a template declaration or definition is obtained by merging the default arguments from the definition (if in scope) and all declarations in scope in the same way default function arguments are (8.3.6). [ Example:

 template<class T1, class T2 = int> class A;
 template<class T1 = int, class T2> class A;

is equivalent to

 template<class T1 = int, class T2 = int> class A;

—end example ]

关于c++ - 为什么 VC++ 允许没有完整模板参数的模板类实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24362039/

相关文章:

c++ - 嵌套模板列表错误

C++ 模板整数类型足够的无符号类型

c++ - 我遇到了可怕的 LNK2019 错误,不知道从这里开始。

c++ - 程序产生的奇怪输出

c++ - 如何使用 boost::asio::io_service 在 C++11 线程之间调度作业

c++ - 如何在C++中复制指针数组的数据

c++ - 没有 PROGMEM 的 Adafruit gfx 库 drawBitmap

c++ - 模板类中运算符+重载值的限制

visual-c++ - MFC - 资源 ID 的唯一性

c++ - (如何)我可以在 Centos/RHEL 上使用新的 C++ 11 ABI 和 devtoolset-7 吗?