我有一些代码(见下文),奇怪的是,当我通过gcc运行代码时它编译得很好,但是当我在Visual Studio 2017中打开相同的文件时,我得到了一个编译器错误:
Error C2440 'reinterpret_cast': cannot convert from '::size_t' to 'Alias'
Run Code Online (Sandbox Code Playgroud)
这是一个你可以尝试的最小例子.只需点击"新项目",选择C++ Windows控制台应用程序,插入此代码,然后尝试在默认的x86-debug模式下编译:
#include "stdafx.h"
#include <cstddef>
typedef std::size_t Alias;
Alias makeAlias(std::size_t n)
{
return reinterpret_cast<Alias>(n);
}
int main()
{
std::size_t x = 1;
Alias t = makeAlias(x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,如果你将return语句更改为这个稍微复杂的变体,它确实可以编译,所以看起来Visual Studio决定reinterpret_cast只允许指针类型:
return *(reinterpret_cast<Alias*>(&n));
Run Code Online (Sandbox Code Playgroud)
这听起来像是Visual Studio的一个奇怪的决定,因为根据cpp引用:
与static_cast不同,但与const_cast类似,reinterpret_cast表达式不会编译为任何CPU指令.它纯粹是一个编译器指令,它指示编译器将表达式的位序列(对象表示)视为具有new_type类型.
所以至少在我看来,如果我尝试reinterpret_cast在两种类型之间以完全相同的方式占用内存,那么reinterpret_cast就是所谓的.毕竟,顾名思义,我将"相同的位模式"重新解释为另一种类型.
我意识到这reinterpret_cast主要是针对指针类型之间的转换,但我不明白为什么我应该被禁止在这样的情况下使用它.在某种"使用正确工作的正确工具"的意义上,允许程序员reinterpret_cast用于其预期目的,而不是强迫他们在static_cast没有必要时使用(更不用说不必要地燃烧这个过程中几个时钟周期)?
在允许reinterpret_castVisual Studio禁止此操作的别名类型之间是否存在某种危险?Reinterpret_cast如果使用不当,我肯定是危险的,但我不明白为什么如果使用得当它会失败(除非我在这种情况下在"正确"使用的定义中缺少某些东西).
所以,我不完全确定这里发生了什么,但无论出于什么原因,Python都在向我抛出这个.作为参考,它是我正在构建的一个小型神经网络的一部分,但是它使用了大量的np.array等,所以有很多矩阵被抛出,所以我认为它正在创建某种数据类型冲突.也许有人可以帮我解决这个问题,因为我一直盯着这个错误太长时间而不能修复它.
#cross-entropy error
#y is a vector of size N and output is an Nx3 array
def CalculateError(self, output, y):
#calculate total error against the vector y for the neurons where output = 1 (the rest are 0)
totalError = 0
for i in range(0,len(y)):
totalError += -np.log(output[i, int(y[i])]) #error is thrown here
#now account for regularizer
totalError+=(self.regLambda/self.inputDim) * (np.sum(np.square(self.W1))+np.sum(np.square(self.W2)))
error=totalError/len(y) #divide ny N
return error
Run Code Online (Sandbox Code Playgroud)
编辑:这是返回输出的函数,因此您可以知道它的来源.y是长度为150的向量,直接从文本文档中获取.在y的每个索引处,它包含1,2或3的索引:
#forward propogation algorithm takes a matrix "X" of size 150 x 3
def …Run Code Online (Sandbox Code Playgroud)