【问题标题】:Why do the two template functions differ in output?为什么两个模板函数的输出不同?
【发布时间】:2018-08-07 07:06:15
【问题描述】:

为什么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

【问题讨论】:

    标签: c++ templates auto type-deduction


    【解决方案1】:

    FuncOne 不是写FuncTwo 的另一种方式。如果你更换了这条线

     auto a = reinterpret_cast<const volatile char &>(v);
    

    通过

     auto& a = reinterpret_cast<const volatile char &>(v);
    

    否则const volatile char&amp; 中的引用将在type-deduction 期间为a 删除。

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多