[英]Distinguish between pass-by-value and pass-by-reference in a function template
Is there a way to let the compiler distinguish whether the passed variable is a reference or not, without explicitly specifying it using eg <int &>
?有没有办法让编译器区分传递的变量是否是引用,而无需使用例如
<int &>
显式指定它? The following example displays '1', whereas I expected a '2':以下示例显示“1”,而我预期的是“2”:
template <typename Type>
void fun(Type)
{
cout << 1 << '\n';
}
template <typename Type>
void fun(Type &)
{
cout << 2 << '\n';
}
int main()
{
int x = 0;
int &ref = x;
fun(ref);
}
I also tried to use std::ref
, but I don't get it to work.我也尝试使用
std::ref
,但我没有让它工作。
template <typename Type, typename = std::enable_if_t<!std::is_reference<Type>::value>>
void fun(Type)
{
std::cout << 1 << '\n';
}
template <typename Type, typename = std::enable_if_t<std::is_reference<Type>::value>>
void fun(Type &)
{
std::cout << 2 << '\n';
}
int main() {
int x = 0;
int &ref = x;
fun<int&>(ref); // Call the one that you want, and don't leave the compiler decide which one you meant
return EXIT_SUCCESS;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.