为什么 FuncOne
和 FuncTwo
这两个模板函数的输出不同?
template <class T>
T * FuncOne(T & v)
{
auto a = reinterpret_cast<const volatile char &>(v);
auto b = & const_cast<char&>(a);
auto c = reinterpret_cast<T *>(b);
return c;
}
template <class T>
T * FuncTwo(T & v)
{
return reinterpret_cast<T *>(& const_cast<char&> (reinterpret_cast<const volatile char &>(v)));
}
测试这两个函数的代码:
int main()
{
nonaddressable na;
nonaddressable * naptr = FuncOne(na);
cout << "FuncOne: naptr = " << naptr << endl;
naptr = FuncTwo(na);
cout << "FuncTwo: naptr = " << naptr << endl;
nonaddressable * nbptr = new nonaddressable;
cout << "Address of nbptr = " << nbptr << endl;
cout << "FuncOne: nbptr = " << FuncOne(*nbptr) << endl;
cout << "FuncTwo: nbptr = " << FuncTwo(*nbptr) << endl;
}
示例输出:
FuncOne: naptr = 0x61fddf
FuncTwo: naptr = 0x61fe2f
Address of nbptr = 0x7216e0
FuncOne: nbptr = 0x61fddf
FuncTwo: nbptr = 0x7216e0
从比较 nbptr
的值我们可以看出,FuncTwo
给出了预期的正确输出。但是为什么 FuncOne
不提供相同的输出,因为它只是另一种编写 FuncTwo
的方式?
使用的编译器:g++ 7.1.0
最佳答案
FuncOne
不是另一种编写 FuncTwo
的方式。如果你更换了这条线,那就是
auto a = reinterpret_cast<const volatile char &>(v);
通过
auto& a = reinterpret_cast<const volatile char &>(v);
否则 const volatile char&
中的引用将在 type-deduction 期间被删除对于 a
。
关于c++ - 为什么这两个模板函数的输出不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51720790/