P.W
P.W

Reputation: 26800

Why do the two template functions differ in output?

Why do the two template functions FuncOne and FuncTwo differ in output?

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)));
}

Code to test the two functions:

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;
}

Sample Output:

FuncOne: naptr = 0x61fddf   
FuncTwo: naptr = 0x61fe2f   

Address of nbptr = 0x7216e0   
FuncOne: nbptr = 0x61fddf   
FuncTwo: nbptr = 0x7216e0 

As we can see from comparing the values of nbptr, FuncTwo gives the expected and correct output. But why does not FuncOne give the same output as it is just another way of writing FuncTwo?

Compiler Used: g++ 7.1.0

Upvotes: 0

Views: 100

Answers (1)

Tobi
Tobi

Reputation: 2749

FuncOne is not another way of writing FuncTwo. It would be if you replaced the line

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

by

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

Otherwise the reference in const volatile char& will be dropped during type-deduction for a.

Upvotes: 4

Related Questions