繁体   English   中英

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

[英]Distinguish between pass-by-value and pass-by-reference in a function template

有没有办法让编译器区分传递的变量是否是引用,而无需使用例如<int &>显式指定它? 以下示例显示“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);
}

我也尝试使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM