如果我有模板:
template <class T>
struct Item
{
T _value;
};
然后我可以做:
// ...
Item<int> x = { 42 }; // declared as an int
// ...
decltype(x._value) y = 20; // 'y' is also an int
但是否可以存储 decltype
到一个变量以便以后可以使用它?
为什么?
我想将项目的值存储为指针。
类似于 std::vector<Item*>
但由于它们是模板,我必须将它们存储为指向 void
的指针:
std::vector<void*> is;
is.push_back(new Item<int>());
is.push_back(new Item<double>());
is.push_back(new Item<float>());
这一切都很好,但是当需要删除指针时,我需要重新转换我的 void*
回到正确的类型(因此调用析构函数):
delete (Item<int>*)is[0];
如果我知道类型,我可以这样做:
delete (Item<decltype(whatever)>*)is[0];
因此我需要存储 decltype
的原因.
我希望这是有道理的。
最佳答案
decltype
是一种语言功能,允许您在编译时检索类型。似乎您想“存储”该类型,以便您可以在运行时正确地 delete
分配在动态存储上的对象。假设是这种情况,decltype
在这里无济于事。
您有多种选择:
按照 Baum mit Augen 的建议,使用某种形式的类型删除工具,例如
Boost.Variant
或Boost.Any
在评论中。使您的对象成为多态层次结构的一部分并使用智能指针:
struct ItemBase { virtual ~ItemBase() { } }; template <class T> struct Item : ItemBase { T _value; }; int main() { std::vector<std::unique_ptr<ItemBase>> items; items.emplace_back(std::make_unique<Item<int>>()); items.emplace_back(std::make_unique<Item<float>>()); items.emplace_back(std::make_unique<Item<double>>()); }
关于c++ - 存储和重新使用 decltype 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38931227/