mardi 1 août 2017

template metaprogramming with reference

I was checking some solutions of the book cpp template metaprogramming for the 1st exercise http://ift.tt/2tWvBGw

> "Write a unary metafunction add_const_ref<T> that returns T if it is a
> reference type, and otherwise returns T const&"

 template<typename T>
 struct add_const_ref
 {
     typedef typename boost::add_const<T>::type ct;
     typedef typename boost::add_reference<ct>::type type;
 };

I revised it with c++11:

 template<typename T>
 struct add_const_ref_type
 {
     typedef typename std::add_const<T>::type ct;
     typedef typename std::add_lvalue_reference<ct>::type type;
 };

i do not understand why it works with reference. I expect this will add const, i.e., change the int& to `const int&.

 int main()
 {   
    std::cout << std::is_same<add_const_ref_type<int &>::type, int&>::value << '\n'; // print 1
    std::cout << std::is_same<add_const_ref_type<int &>::type, const int&>::value << '\n'; // print 0

    return 0;
 }

Aucun commentaire:

Enregistrer un commentaire