当将指向派生类而不是基类的指针作为模板指针参数时,我遇到了一个问题。 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/