【问题标题】:Distinguish between pass-by-value and pass-by-reference in a function template区分函数模板中的值传递和引用传递
【发布时间】:2020-02-29 00:09:35
【问题描述】:

有没有办法让编译器区分传递的变量是否是引用,而无需使用例如显式指定它<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,但我无法使用它。

【问题讨论】:

  • 你用的是什么编译器?这看起来不像有效的 C++,我相信这些调用应该是模棱两可的。大多数编译器都同意:godbolt.org/z/ovW5QB
  • @DeducibleSteak 是的,我也是这么想的,但是为什么编译器允许定义这样的方法呢? (我使用的是 Apple Clang,它允许我定义这两种方法)
  • @farzadshbfn 这很可能是您的编译器中的一个错误。
  • 这引起了我的兴趣,Jasper,所以我尝试使用 g++ 8.3.0 构建程序并得到了预期的错误。使用的编译器选项:-std=c++17 -O0 -g3 -pg -pedantic -Wall -Wextra -Wconversion -c -Wuninitialized 你使用什么选项?
  • @JasperKoning,无论如何,您将无法像那样区分。 fun(x)fun(ref) 在调用站点的参数类型将相同:int&amp;。但我无法用权威链接回答,将它留给有更多语言 - 律师 - foo 的人。

标签: c++ templates reference


【解决方案1】:
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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 2013-10-26
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多