c++ - 使用指向派生类的指针作为模板参数时出错

标签 c++ templates pointers

当将指向派生类而不是基类的指针作为模板指针参数时,我遇到了一个问题。 E.i.以下代码:

class First{};
class Second : public First {};

template<First* ptr> class Third {};

Second obj;

int main(){
    Third<&obj> obj2;
}

编译时返回错误:

error C2440: 'specialization' : cannot convert from 'Second *' to 'First *'

有什么办法可以克服这个问题吗?我知道,我可以将指针作为参数传递给 Third 的构造函数,而不是它的模板参数,但我想用不同的指针来区分类 Third 的对象在编译的那一刻,所以只能使用 Third 的对象和在给定上下文中适当的指针。

最佳答案

模板类型推导没有进行隐式类型转换,因此您的示例无法编译。

相关:C++ Templates type casting with derivates

在非模板代码中,一切正常,例如

First *p = &obj;

工作得很好。

您的示例与

具有相同的风格
template <int N>
void f(){}

int main()
{
    f<42.42>(); // fails, double is not converted to int here
}

error: conversion from 'double' to 'int' not considered for non-type template argument

关于c++ - 使用指向派生类的指针作为模板参数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30791783/

相关文章:

c++ - 将一个方面应用于所有流输出,使用自定义字符串操纵器

c++ - 将文本文件读入矩阵,然后将它们相乘

c++ - chrono::high_resolution_clock 延迟不一致

javascript - RequireJS - Marionette ItemView 上的延迟加载模板

c++ - 在处理模板时,如何避免在函数头和函数体中两次声明相同的类型?

C++ : Null pointers and structs

c++ - 如果被外层调用者捕获,C++ 异常是否超出范围?

c++ - 使用具有前向声明类型的模板 - 安全吗?

c++ - 我在 C 中遇到指针问题

c++ - 无法创建 char * 对象以发送到 c++/c 共享对象库