squ*_*les 5 c++ types typeid decltype boost-variant
我有boost::variant多种类型,例如:
typedef boost::variant< uint8_t, int8_t, uint16_t, int16_t,
uint32_t, int32_t, float, double, std::string > StorageTt;
Run Code Online (Sandbox Code Playgroud)
稍后在我的代码中将变量StorageTt(例如 )val设置为这些存储类型之一。我想检索当前保存的类型val以定义更多相同类型的变量。所以如果val当前是 a uint16_t,我想做类似的事情:
typedef decltype(typeid(val)) StorageTt;
StorageTt new_val = 42; // new_val should be a uint16_t
Run Code Online (Sandbox Code Playgroud)
但这会产生一个const type_info类型。我知道我能做到:
switch (val.which()) {
case 0: // uint8_t
case 1: //...
Run Code Online (Sandbox Code Playgroud)
但我宁愿避免长 switch 语句,因为我必须多次执行此操作。
您可以使用带有调用运算符模板的访问者函子来执行类似的操作:
struct MyVisitor : public boost::static_visitor<>
{
template <typename StorageT>
void operator()(const StorageT&) const
{
StorageT new_val = 32; // declare variable with same type
doSomethingWith(new_val); // do something with it
}
};
Run Code Online (Sandbox Code Playgroud)
将其应用到变体中,val如下所示:
boost::apply_visitor(MyVisitor(), val);
Run Code Online (Sandbox Code Playgroud)
参考:
我不知道用 C++14 泛型 lambda 替换函子的方法。