c++ - 错误 C2440:“正在初始化”:无法从“const mynamespace::mytype*”转换为“const T*”
问题描述
我有这两个cpp文件。当我尝试编写模板函数Method()
时,出现 C2440 错误。
我尝试了三种不同的方式来完成任务。只有 C 风格的强制转换才能通过编译器。
我想知道如何以 C++ 风格做到这一点。
谢谢 : )
FileA:
template <typename T>
int ClassName<T>::Method(params...)
{
const T* temp = (T*)GetValueArray(); // C-style cast, right √
const T* temp = GetValueArray(); // no cast, error C2440
const T* temp = static_cast<T*>(GetValueArray()); // error C2440, reinterpret or
// const or dynamic_cast all C2440
}
_______________
FileB:
typedef double mytype;
const mynamespace::mytype* GetValueArray() const
{
mynamespace::mytype res[3] = {1,2,3};
return res;
}
#include <iostream>
typedef double MyType;
const MyType* GetValueArray()
{
MyType* ptr = new MyType;
*ptr = 20.20;
return ptr;
}
template <typename T>
void Method()
{
const T* temp = (T*)GetValueArray(); // C-style cast, right √
//const T* temp = GetValueArray(); // no cast, error C2440
//const T* temp = static_cast<T*>(GetValueArray()); // error C2440, reinterpret or
// const or dynamic_cast all C2440
std::cout << *temp;
}
int main(int argc, char* argv[])
{
Method<double>();
}
我得到输出 20.2。在这里我可以得到正确的结果,因为T
is just double
。在这种情况下,使用 lost const
,程序可以通过编译器。
但是如果我改成Method<int>
,不管结果是什么(实际上结果是无用的数字),但是为什么会出现C2440呢?
解决方案
你的演员失去了 const-ness
const T* temp = static_cast<const T*>(GetValueArray());
C 风格的演员表起作用的原因是它尝试的演员表之一,const_cast
在这种情况下,这可能不是你想要的。
推荐阅读
- javascript - 保存时测试失败(在测试脚本配置中使用`--watch`)但是如果我手动重新运行它们会通过吗?
- docker - docker容器启动后如何设置环境变量
- python - 尝试使用另一个stackoverflow答案中的矢量角度公式,但无法让它打印角度
- pandas - read_csv() 中的 skiprows 参数有什么作用?
- c# - 从 CosmosDB ChangefeedObserver 文档中获取对象类型
- selenium - 使用 Protractor 并行自动化测试的正确配置设置是什么?
- javascript - 向数组 React 添加一个对象;“TypeError:无法读取未定义的属性‘push’”
- kubernetes - 如何在 OpenShift 上为我的应用程序选择名称
- java - 如何在 Java 光线追踪器中实现多线程
- javascript - 如何从此键值对中获取给定的突出显示文本信息