存储和重新使用decltype值?

Sim*_*man 10 c++ templates decltype c++11

如果我有一个模板:

template <class T>
struct Item
{
  T _value;
};
Run Code Online (Sandbox Code Playgroud)

然后我可以这样做:

// ...
Item<int> x = { 42 }; // declared as an int

// ...
decltype(x._value) y = 20; // 'y' is also an int
Run Code Online (Sandbox Code Playgroud)

但是可以将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>());
Run Code Online (Sandbox Code Playgroud)

这一切都很好,但是当需要删除指针时,我需要将我的void*表格重新转换为正确的类型(因此调用析构函数):

delete (Item<int>*)is[0];
Run Code Online (Sandbox Code Playgroud)

如果我知道类型,我可以这样做:

delete (Item<decltype(whatever)>*)is[0];
Run Code Online (Sandbox Code Playgroud)

因此我需要存储的原因decltype.

我希望这是有道理的.

Vit*_*meo 6

decltype是一种语言功能,允许您在编译时检索类型.您似乎希望"存储"该类型,以便您可以delete在运行时正确分配在动态存储上的对象.假设是这样的话,decltype在这里不会有帮助.

你有各种选择:

  1. 使用某种形式的样型擦除设施Boost.Variant或者Boost.Any,如建议鲍姆MIT眼球中的注释.

  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>>());
    }
    
    Run Code Online (Sandbox Code Playgroud)


sky*_*ack 5

如果问题只是删除它们,您可以使用unique_ptr自定义删除器而不是裸指针.
您无需修改​​层次结构即可执行此操作.
举个例子:

std::vector<std::unique_ptr<void, void(*)(void*)>> is;
is.push_back(std::unique_ptr<void, void(*)(void*)>{new Item<int>(), [](void *ptr) { delete static_cast<Item<int>*>(ptr); }}); 
Run Code Online (Sandbox Code Playgroud)

如果使用emplace_back而不是push_back:更好:

std::vector<std::unique_ptr<void, void(*)(void*)>> is;
is.emplace_back(new Item<int>(), [](void *ptr) { delete static_cast<Item<int>*>(ptr); }); 
Run Code Online (Sandbox Code Playgroud)

它遵循基于OP代码的最小工作示例:

#include<vector>
#include<memory>

template<typename>
struct Item {};

int main() {
    using Deleter = void(*)(void*);
    std::vector<std::unique_ptr<void, Deleter>> is;
    is.emplace_back(new Item<int>(), [](void *ptr) { delete static_cast<Item<int>*>(ptr); }); 
    is.emplace_back(new Item<double>(), [](void *ptr) { delete static_cast<Item<double>*>(ptr); }); 
    is.emplace_back(new Item<float>(), [](void *ptr) { delete static_cast<Item<float>*>(ptr); }); 
}
Run Code Online (Sandbox Code Playgroud)