简体   繁体   English

区分函数模板中的值传递和引用传递

[英]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.

相关问题 C ++中按值传递和按引用传递之间的区别 - Differences between pass-by-value and pass-by-reference in c++ 函数参数按值传递比按引用传递更快? - Function argument pass-by-value faster than pass-by-reference? 将按引用传递和按值传递混合到可变参数模板函数是否有效? - Mixing pass-by-reference and pass-by-value to variadic template function valid? 区分传递参考和传递价值 - Distinguishing Pass-by-Reference and Pass-by-Value 如何获得模板参数包来推断按引用而不是按值? - How do I get a template parameter pack to infer pass-by-reference rather than pass-by-value? 我应该在哪里更喜欢按引用传递或按值传递? - Where should I prefer pass-by-reference or pass-by-value? 值传递和 std::move 优于传递引用的优点 - Advantages of pass-by-value and std::move over pass-by-reference 通过查看装配将值传递与引用传递性能进行比较 - Comparing pass-by-value with pass-by-reference performance by looking at assembly C++:赋值运算符:按值传递(复制和交换)与按引用传递 - C++: assignment operator: pass-by-value (copy-and-swap) vs pass-by-reference 我可以让C ++编译器决定是按值传递还是按引用传递? - Can I let the C++ compiler decide whether to pass-by-value or pass-by-reference?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM