Template default argument loses its reference type

依然范特西╮ 提交于 2019-12-03 04:12:06

For foo<int>(a), ARG_T is being deduced from a, and is not taken from the default template argument. Since it's a by value function parameter, and a is an expression of type int, it's deduced as int.

In general, default template arguments are not used when template argument deduction can discover what the argument is.

But we can force the use of the default argument by introducing a non-deduced context for the function parameter. For instance:

template <class T, class ARG_T = T&>
T foo(std::enable_if_t<true, ARG_T> v1){
    //...
}

Or the C++20 type_identity utility, such as the other answer demonstrates.

You need to stop template argument deduction for ARG_T from the function argument v, (with the help of std::type_identity, which could be used to exclude specific arguments from deduction); Otherwise, the default template argument won't be used. e.g.

template <class T, class ARG_T = T&>
T foo(std::type_identity_t<ARG_T> v){
    return std::is_reference<decltype(v)>::value;
}

LIVE

BTW: If your compiler doesn't support std::type_identity (since C++20), you might make your own.

template<typename T> struct type_identity { typedef T type; };
template< class T >
using type_identity_t = typename type_identity<T>::type;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!