c++ - 派生为模板参数的基本转换

标签 c++ templates derived-class

struct CL1{};
struct CL2:CL1{};

template<CL1*>
struct TMPL{};

CL2 cl2;

int main()
{
    TMPL<&cl2> tmpl; //error: could not convert template argument ‘& cl2’ to ‘CL1*’
    return 0;
}

标准 2003 14.3.2/5 说:

for a non-type template-parameter of type pointer to object, qualification conversions (4.4) and the array-to-pointer conversion (4.2) are applied. [Note: In particular, neither the null pointer conversion (4.10) nor the derived-to-base conversion (4.10) are applied. Although 0 is a valid template-argument for a non-type template-parameter of integral type, it is not a valid template-argument for a non-type template-parameter of pointer type. ]

为什么要施加这样的限制?

最佳答案

2 个原因恕我直言:

  1. 地址直到链接时才为人所知。那是在做出任何模板扩展决定之后。事实上,在与位置无关的代码中,地址直到运行时才为人所知。

  2. (type *)0 和 int(0) 之间长期以来存在歧义。 c++11 使用 nullptr_t 类的 nullptr 值解决了这个问题。

关于c++ - 派生为模板参数的基本转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27625392/

相关文章:

c++ - new int[M][N] 的类型是什么?

c++ - 如何在 C++ 中创建任意函数的字符串参数化包装器?

C++ 模板和重载运算符

c++ - 具有不同访问权限的类 : read-only to the many, 可写入特权

c# - 是否可以将属性参数从派生类传递到其基类?

c++ - Boost C++ 序列化一个 char *

c++ - 在空指针的情况下,shared_ptr 和 unique_ptr 的删除器的标准行为是否不同?

c++ - 来自 Omnet++ 网络的柠檬图

c++ - 可以对 lambda 函数进行模板化吗?

c++ - 指向基类数组的指针,用派生类填充