c++11/14 make_unique对std::string的异常重载

c++11/14 make_unique ambigious overload for std::string

本文关键字:string 异常 重载 std make unique c++11      更新时间:2023-10-16

有人能解释一下如何解决make_unique的异常过载警告吗,错误来自哪里,它的确切含义是什么(我确实理解什么是异常过载,但我不确定为什么我会为这个特定的代码得到一个)?我使用的是c++11,因此我使用了Herb Sutter推荐的模板。

使用它我得到以下错误:

Error   4   error C2668: 'make_unique' : ambiguous call to overloaded function

visualstudio13中悬停在工具提示上给了我以下方法:

function template "std::enable_if<!std::is_array<_Ty>::value, std::unique_ptr<_Ty,std::default_delete<_Ty>>>::type std::make_unique<_Ty,_Types...>(_Types &&..._Args)"
function template "std::unique_ptr<T, std::default_delete<T>> make_unique<T,Args...>(Args...)
argument types are: std::string

第二个应该是从make_unique模板调用的

/* Will be part of c++14 and is just an oversight in c++11
 * From: http://herbsutter.com/gotw/_102/
 */
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique(Args&& ...args){
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

要转发到的构造函数:

Shader(const std::string& name);

生成错误的代码

std::string _name = "Shader";
std::unique_ptr<Shader> s = make_unique<Shader>(_name); 

调用不明确,因为确实具有std::make_unique,如您引用的工具提示内容所示。尽管您没有编写std::,但由于您正在传递一个依赖于std::string参数的查找,因此会自动搜索该命名空间。

当你说"我正在使用C++11"时,这并不完全正确,因为Visual Studio不允许你选择用哪种标准编写。它只是为你提供了它为任何给定功能所收集的最新支持。显然,Visual Studio 2013有C++14的std::make_unique

移除您的。