gpt4 book ai didi

c++ - C++模板避免两次传递元素类型

转载 作者:行者123 更新时间:2023-12-01 15:07:48 25 4
gpt4 key购买 nike

我有一个模板化的类,我需要将容器和容器的元素都作为模板参数传递。例如:

template<class CONTAINER, class ELEMENT>
class M
{
void addElement(const ELEMENT e){}
CONTAINER container;
};
所以该类将被实例化为:
M<std::array<CustomType, SIZE>, CustomType> m;
如您所见, CustomType通过了两次。
有避免这种情况的优雅方法吗?问题是我不知道容器的类型是什么,因此需要单独传递。

最佳答案

我可以提出两个选择:

  • 使用所有标准容器都具有的value_type成员类型:
    template<class CONTAINER>
    class M {
    using ELEMENT = typename CONTAINER::value_type;
    // ...
    };
  • 从某些成员函数中获取元素类型。例如:
    template<class CONTAINER>
    class M {
    using ELEMENT = std::decay_t<decltype(std::declval<CONTAINER>()[0])>;
    // ...
    };
  • 关于c++ - C++模板避免两次传递元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63152981/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com