【发布时间】:2021-04-30 02:53:25
【问题描述】:
我正在编写一个固定大小的容器类型,放置新。 当我测试它时,我发现如果类型 T 有明确的 ctor,我的“emplace_back()”之类的函数就不会编译。
这是一个代码示例(缺少删除调用等):
#include <iostream>
template <typename T>
struct TestType
{
explicit TestType(T value) // removing explicit makes it a compileable code
{
std::cout << value << std::endl;
}
};
template <typename... Args>
void emplace(TestType<int>* buffer, Args&&... args)
{
// placement new // compile time error in this line
new (buffer) TestType<int>(std::forward<TestType<int>>(args)...);
}
int main()
{
TestType<int>* buffer;
buffer = (static_cast<TestType<int>*>(::operator new(sizeof(TestType<int>) * 10)));
emplace(buffer, 5);
return 0;
}
错误是: " 在 'void emplace(TestType*, Args&& ...) [with Args = {int}]' 的实例化中: 24:22:从这里需要 16:64:错误:没有匹配的函数调用'forward(int&)'"
stackoverflow 上有一些类似的问题,但是这些主要是关于 std::map 的,可能我的问题不同。 (如果没有,我仍然不明白发生了什么。)
如果(例如)std::vector emplace_back() 适用于任何具有显式 ctor 的 T 类型,为什么它不适用于我的容器类型? 这编译得很好:
#include <iostream>
#include <vector>
template <typename T>
struct TestType
{
explicit TestType(T value)
{}
};
int main()
{
std::vector<TestType<int>> vector;
vector.emplace_back(5);
return 0;
}
感谢您的帮助!
【问题讨论】:
标签: c++ perfect-forwarding placement-new explicit-constructor