c++ - 存储和重新使用 decltype 值?

标签 c++ templates c++11 decltype

如果我有模板:

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 在这里无济于事。

您有多种选择:

  1. 按照 Baum mit Augen 的建议,使用某种形式的类型删除工具,例如 Boost.VariantBoost.Any在评论中。

  2. 使您的对象成为多态层次结构的一部分并使用智能指针:

    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/

相关文章:

C++11:我可以从多个 args 转到 tuple,但我可以从 tuple 转到多个 args 吗?

c# - ReadMsgQueue 返回 ERROR_INVALID_PARAMETER

c++ - iostream 是否使用重载或模板?

C++类模板继承之谜

c++ - 在智能指针的双图中查找原始指针

c++ - 网络编程基础知识,需要帮助才能理解 addrinfo/sockaddr_in 结构用法等

c++ - 如何在 OpenCV 中将点传递给 cvFitEllipse2

C++ - 将类型映射到枚举

c++ - 如何将成员模板类声明为封闭类的友元?

c++ - 有没有办法在容器中存储不同的函数指针类型