How to combine type restrictions and implicit conversions with C ++ 11 generic references?

In the function, I need to distinguish between lvalue and rvalue references, so the obvious way is to overload:

void myfunc(A&& a);
void myfunc(const A& a);

This has the desired behavior with a well-defined type and implicit conversion. However, there is too much code duplication, and I would prefer to encapsulate the corresponding solutions inside, while retaining only one function, so passing a universal link may be an option:

template <typename A>  void myfunc(A&& a);

However, this has an unfortunate drawback that now any object can be passed as the first parameter, so you can impose restrictions through enable_if:

template <typename T, class  = typename enable_if<
    is_same<typename remove_const<typename    remove_reference<T>::type>::type, A>::value,
    T>::type>   
void myfunc( T&&  a);

, ( , ) , A (, C). , 3 A && , . - ? , , , A , , , explicits implicits ( C lvalue [reference] rvalue ). ?

+4
1

std::is_convertible :

template <typename T, 
          class = typename enable_if<is_convertible<T, A>::value>::type>   
void myfunc( T&&  a);
+5

Source: https://habr.com/ru/post/1628848/


All Articles