我想初始化一个静态的std::map
,其中值是不可复制的。 我将我的类称为ValueClass。 ValueClass 有一个私有成员std::unique_ptr
,我甚至通过扩展看起来像以下内容的non_copyable
来确保ValueClass
是不可复制的:
class non_copyable {
public:
non_copyable() = default;
protected:
virtual ~non_copyable() = default;
private:
non_copyable(const non_copyable&) = delete;
non_copyable& operator=(const non_copyable&) = delete;
};
现在我正在尝试使用我的类作为值来定义一个std::map:
static std::map<int, ValueClass> value_classes = {
{0, ValueClass()},
{1, ValueClass() }
};
我遇到编译错误,因为initializer_list
试图复制这个类。
我尝试了整个周末写我的自己的make_map
函数,以实现初始化而不进行复制,但是我失败了。我尝试了这个,那个和其他的,但是它们都无法在Visual Studio 15.9.4中编译。
如何初始化静态std::map,其中不强制进行复制,并且在一个函数中统一初始化,使用Visual Studio编译器?
编辑: 这里是实际情况的简化版本,我正在尝试让它工作(对于缺乏命名规范和大小写不一致,请原谅):
#include <iostream>
#include <map>
class non_copyable {
public:
non_copyable() = default;
protected:
virtual ~non_copyable() = default;
private:
non_copyable(const non_copyable&) = delete;
non_copyable& operator=(const non_copyable&) = delete;
};
class InnerValueClass : public non_copyable
{
public:
InnerValueClass(const int inner_number) : inner_number_(inner_number) { }
private:
int inner_number_;
};
class ValueClass : public non_copyable
{
public:
ValueClass(const int number1) : number1_(number1) { }
ValueClass(const bool condition) : condition_(condition), inner_value_(
std::make_unique<InnerValueClass>(5)) { }
private:
int number1_{};
bool condition_{};
std::unique_ptr<InnerValueClass> inner_value_{};
};
/* Inline initialization of std::map copies, this is for initialization of non-copy types*/
template <typename TKey, typename TNonCopyableValue>
class make_map_by_moving
{
typedef std::map<TKey, TNonCopyableValue> map_type;
map_type map_;
public:
make_map_by_moving(const TKey& key, TNonCopyableValue&& val)
{
map_.emplace(key, std::move(val));
}
make_map_by_moving<TKey, TNonCopyableValue>& operator()(const TKey& key, TNonCopyableValue&& val)
{
map_.emplace(key, std::move(val));
return *this;
}
operator const map_type&()
{
return map_;
}
};
static std::map<int, ValueClass> map =
make_map_by_moving<int, ValueClass>
(1, ValueClass(5))
(2, ValueClass(true));
/* It goes on like this for hundreds of lines, so I really appreciate any
solution that leave me with a clean initialization rather than calling
functions on std::map */
int main() { }
重复编辑:那个问题中提供的解决方案不适用于我拥有的类结构。我还在寻找一种解决方案来修复make_map_by_moving
函数,换句话说是内联初始化,那里提供的答案是带有函数调用的命令式解决方案。