【发布时间】:2016-06-24 23:10:37
【问题描述】:
此代码适用于 Visual Studio:
typedef struct {
int a;
} data_t;
using datap_t = std::unique_ptr<data_t>;
using MyPair = std::pair<std::string, datap_t>;
int main() {
data_t * pd1 = new data_t();
MyPair p("tst", pd1); // This does not compile in gcc or clang
// MyPair p2("tst", datap_t(pd1)); // This compiles
return 0;
}
但是 clang 和 gcc 给出错误:
error: no matching function for call to 'std::pair<const std::basic_string<char>, std::unique_ptr<data_t> >::pair(const char [3], data_t*&)
Here 是可以尝试的理想人选。
我可以调用datap_t(pd1) 并且它编译的事实意味着构造函数是有效的,那么为什么该模板找不到合适的匹配?
我希望使用 emplace 将键值对添加到地图中,这就是为什么我希望首先进行这种隐式转换。请注意,与 Visual Studio 一样,隐式转换适用于大多数其他类型,例如 std::string 来自 "raw string"。
This answer 看起来很相关,但它谈到了一个已修复的错误并且非常古老。
【问题讨论】:
-
不要使用原始指针。
auto pd1 = std::make_unique<data_t>(). -
@kfsone 我没有,在处理外部 C 库时,处理原始指针是不可避免的。另外,我很想知道为什么这在 Visual Studio 中有效,而不是当叮当响,而不是寻找如何使它工作:)