问题描述
考虑
#include <iostream>
#include <type_traits>
template <class T, class ARG_T = T&>
T foo(ARG_T v){
return std::is_reference<decltype(v)>::value;
}
int main() {
int a = 1;
std::cout << foo<int>(a) << '\n';
std::cout << foo<int, int&>(a) << '\n';
}
我希望两种情况下的输出均为1.但是在第一种情况下,它是0:与默认值class ARG_T = T
而不是class ARG_T = T&
一致.
I'd expect the output to be 1 in both cases. But in the first case it's 0: consistent with the default being class ARG_T = T
rather than class ARG_T = T&
.
我想念什么?
推荐答案
对于foo<int>(a)
,ARG_T
是从a
推导出的,而不是从默认模板参数中获取的.由于它是一个按值函数参数,并且a
是类型int
的表达式,因此推导为int
.
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){
//...
}
或C ++ 20 type_identity
实用程序,如其他答案所示.
Or the C++20 type_identity
utility, such as the other answer demonstrates.
这篇关于模板默认参数丢失其引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!