C++ 引物模板通用参考和参数推导

Ita*_*iwa 7 c++ template-argument-deduction

你好,我有一个来自 C++ 入门的例子:

 template <typename T>
 void f(T&& x) // binds to nonconstant rvalues
 {
     std::cout << "f(T&&)\n";
 }

 template <typename T>
 void f(T const& x) // lvalues and constant revalues
 {
     std::cout << "f(T const&)\n";
 }
Run Code Online (Sandbox Code Playgroud)

这是我测试输出的尝试:

int main(){

    int i = 5;
    int const ci = 10;

    f(i); // f(T& &&) -> f(int&)
    f(ci); // f(T const&) -> f(int const&)
    f(5); // f(T &&) -> f(int&&)
    f(std::move(ci)); // f(T&&) -> f(int const&&)

    cout << '\n';
}
Run Code Online (Sandbox Code Playgroud)

输出:

f(T&&)
f(T const&)
f(T&&)
f(T&&)
Run Code Online (Sandbox Code Playgroud)
  • 在书中,f采用转发引用的版本据说仅绑定到非常量右值,但在书中main我传递了一个常量右值f(5),f(std::move(ci))但仍然是调用的第一个版本。

  • 有没有办法调用第二个版本f(T const&)传递右值?我知道我可以明确地做到这一点:f<int const&>(5);或者f<int const&>( std::move(ci) );但我想知道在哪里可以调用传递右值?谢谢你!

  • 我认为转发参考版本之后的注释f不正确:f(T&&) // binds to nonconstant rvalues因为它可以绑定到常量右值,例如:

      f(std::move(ci)); // f(int const&&) and not
      f(int const&)
    
    Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 2

显然,书中的评论并不完全正确。当你有两个可用的重载时

template <typename T> void f(T&& x);
template <typename T> void f(T const& x);
Run Code Online (Sandbox Code Playgroud)

它们都可以用任何参数调用(除了一些例外,我将在此处省略),但如果参数是左值,则首选const第二个。由于推导模板参数时应用的引用折叠规则,在所有其他情况下都首选第一个。

但是,假设这T是由封闭类修复的:

template <class T>
struct S {
    void f(T&& x);
    void f(T const& x);
};
Run Code Online (Sandbox Code Playgroud)

我们假设这T是一个非const对象类型。现在,情况不同了,因为T调用 时没有推导出f。书中的评论似乎指的是后一种情况,其中第一个现在可以使用类型的非右值来调用,但不能使用类型的右值或(可能)的左值来调用。不幸的是,代码与注释不匹配。S::fconstTconstTconstT

让我们回到书中的实际代码。正如我所说,T const&当参数是const左值时,函数采用将是首选。假设参数是5,但您想要显式调用第二个函数,即使它通常不会被选择。有几种方法可以做到这一点。最容易阅读的方法是将参数实际转换为const左值:

f((const int&)5);
Run Code Online (Sandbox Code Playgroud)

Your suggestion of f<const int&>(5) also works, but is a bit more confusing. The reason why it is confusing is that it requires the reader of the code to actually do the reference collapsing mentally and then remember that the first overload is less specialized than the second one. A third method is:

static_cast<void(*)(int const&)>(&f)(5);
Run Code Online (Sandbox Code Playgroud)

Although this one is the hardest to read, the part before the (5) can be used whenever one particular overload needs to be extracted and bound to a function pointer.