【问题标题】:c++11/14 make_unique ambigious overload for std::stringc++11/14 make_unique 模糊重载 std::string
【发布时间】:2015-02-15 00:28:51
【问题描述】:

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

使用它我得到以下错误:

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

Visual Studio 13 中的鼠标悬停在工具提示上为我提供了以下方法:

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); 

【问题讨论】:

    标签: c++ templates c++11 c++14


    【解决方案1】:

    调用不明确,因为您确实拥有std::make_unique,如您引用的工具提示内容所示。即使你没有写std::,因为你传递的是std::stringargument-dependent lookup kicks in to search that namespace automatically

    当您说“我正在使用 C++11”时,这并不完全正确,因为 Visual Studio 不允许您选择要编写的标准。它只是为您提供它为任何给定的标准所收集的最新支持特征。而且,很明显,Visual Studio 2013 有 C++14 的std::make_unique

    删除你的。

    【讨论】:

    • 好收获。但剩下的问题是为什么 VS 将两者都视为候选人。 OP 可能使用了using namespace std;?这是 OP 应该解决的另一件事。
    • 这是我的第一个猜测,我已经扫描了所有文件以使用命名空间 std;可悲的是,这不是问题 :( 任何命名空间都不再使用 using 命名空间了,我不明白为什么 VS 确实看到了 C++14 方法 :) 我是否遗漏了什么,或者它是否有可能使用 std 版本不再使用命名空间了吗?我很确定答案本身是正确的,但我等待批准,直到有人找到或解释为什么使用 C++14 方法。
    • 好的,答案肯定是正确的,因为 ::make_unique(_name) 解决了它。还有一个额外的小问题,为什么 VS 确实看到了 c++14 方法而没有给出命名空间。另一个问题,如果我只是使用 c++14 方法,除了显然需要一个支持 c++14 的编译器来构建项目之外,还有一些我需要注意的事情吗?
    • 再想一想,我同意了你的回答,因为我找不到不使用 c++14 版本的论据,你能想到一个吗?
    • @LightnessRacesinOrbit 是 ADL,我认为问题是编译器不知道 make_uniquetemplate-name 当你没有全局范围版本,所以它无法解析&lt;coliru.stacked-crooked.com/a/33fc5b4228e53f63
    猜你喜欢
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 2012-01-23
    • 2014-03-27
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多