std :: variant vs std :: any当type是move constructible时

0xB*_*F00 4 c++ performance types c++17

如果我有一个类型,std::is_nothrow_move_constructible我需要将它存储在一个std::anystd::variant哪个,你会建议使用哪个,为什么?哪一个会产生最少的开销?编辑:std::variantvs 的不同用例有哪些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;
}
Run Code Online (Sandbox Code Playgroud)

gsa*_*ras 9

如果您知道类型,请使用std::variant.在这种情况下,您知道所有可能的类型,并使用std :: variant :: visit()将访问者应用于变体.

如果不这样做,请使用std::any.在处理通用类型时,您可以考虑这一点.换句话说,当类型不知道apriori.


哪一个会产生最少的开销?

std::variant,不能使用堆.这是不允许的.如果没有动态分配,就没有办法实际拥有包含自身可能变体的结构,因为如果静态声明,这样的结构可以很容易地显示为无限大小.来源.

相反,std::any可能会这样做.因此,第一个将具有更快的构造和复制操作.