如果我有一个类型是
std::is_nothrow_move_constructible
,并且需要将其存储在std::any
或std::variant
中,您会建议使用哪个?为什么?哪一个会产生最少的开销?编辑:在使用std::variant
和std::any
方面有不同的用例吗?class MyType
{
public:
MyType(const MyType&) = default;
MyType(MyType&&) = default;
MyType() = default;
};
int main(int argc, char* argv[])
{
static_assert(std::is_nothrow_move_constructible<MyType>::value, "Not move constructible");
return 0;
}
std::any
基本上是围绕void*
包装有用操作的封装。 - Calethstd::variant
,您需要枚举可能的类型。如果您知道所有这些类型,那么最好,因为您能够处理它们所有。 (参见:variant::visit()
)但是,对于std::any
,您应该为“意外”类型提供默认情况。 - titapo