A brief analysis of the implementation mechanism of std::declval in C++11

  • 2020-05-26 09:39:56
  • OfStack

This paper mainly introduces the C++11 std::declval implementation mechanism of the relevant content, to share out for your reference and learning, the following 1 to look at the detailed introduction:

In vs2013, declval is defined as follows


template <_Ty>
 typenamea dd_rvalue_reference<_Ty>::type declval() _noexcept;

Among them, add_rvalue_reference Is 1 traits, defined as


template <_Ty>
struct add_rvalue_reference
{
 typedef _Ty&& type;
}

As you can see, declval is defined as a function and is declared only, with no implementation (there seems to be an implementation in the gcc version, but it can't be called at runtime either -- via static assertions). So, the question is, why do you define it this way? Why don't you just use the template parameters?

By returning a value from a function, you're essentially instantiating an object of that type, and then you can use that object to call member methods, member variables. The best thing about this method is that you can get an instance of a reference to an image of a type regardless of how it is constructed, or even whether it is constructed or not.
There are other ways to get similar results.


class Klass
{
 public:
  int m_a;
 //parameter defined
 //member function
}

If you have a class above, you can refer to the member variable m_a by:


((Klass*)0)->m_a;

This is also a common technique used in c to get the address offsets of the members of a structure, but it is not as elegant as declval because it has strong Numbers and types.

Of course, all of these 1's can only jump at compile time. declval often works with c++11, the newly introduced decltype.

conclusion


Related articles: