为什么转发参考不起作用?

时间:2016-06-27 13:47:23

标签: c++11 forwarding-reference

我对这段代码有疑问:

#include <string>
#include <iostream>

struct A{
    template<class UT>
    A(UT &&s) : internal(std::forward<std::string>(s)){

    }

    std::string internal;
};

int main(){
    const std::string &s = "hello";

    A a1{ s };

    std::cout << "s = " << s << std::endl;
}

此当前示例未编译,如果我将s更改为非const,则会移动字符串。

我有类似的代码可以正常工作,但在这种情况下有一些我看不到的错误。

1 个答案:

答案 0 :(得分:0)

您正在错误地使用转发引用。您没有给std::forward目的地类型。你给它推导出的模板:

A(UT &&s) : internal(std::forward<UT>(s)){