c++ - 为什么这两个模板函数的输出不同?

标签 c++ templates auto type-deduction

为什么 FuncOneFuncTwo 这两个模板函数的输出不同?

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/

相关文章:

c++ - 让 GDB 显示模板参数的类型

twitter-bootstrap - 将 Bootstrap 模板集成到 cakephp

c++ - Null<std::string> 问题

c++ - 将 `auto` 关键字与 STL 迭代器一起使用

C++ 相当于 Perl 中的 'pack'

c++ - 使用指针搜索值

c++ - 所需输出后出现 glibc 错误

c++ - 从 boost::adjacency_list 获取边属性(包括相关顶点)

c++ - 我可以使用 auto 或 decltype 代替尾随返回类型吗?

C++ 错误 : no matching function for call to 'print_size'