声明模板的共享指针

时间:2018-02-17 09:43:21

标签: c++ c++11 templates

我的课程模板在我的

中如下所示

Counter.hpp

template <typename T1, size_t Count>
class Counter {
public:

    explicit Counter();
    ~Counter() = default;

    void inc(T1 t, uint64_t val);

    void dec(T1 t, uint64_t val);

private:

    uint16_t array[Count];
};

Main.cpp文件

我能够像这样创建一个对象:

Counter< MetricCounter1Type, countOfMetricCounter1Type()> myCounter;

并使用对象....但我希望能够像指针声明那样在堆上创建一个对象:

using counterp = std::shared_ptr <Counter>;

counterp myCounter1p = std::make_shared<Counter<T1type, n>>;
counterp myCounter2p = std::make_shared<Counter<T2type, m>>;

我理解这是一个微不足道的问题,对模板和共享指针不熟悉,有很多东西可以解决这个问题

所以基本上问题是你可以像上面那样创建一个通用的共享指针类型并实例化对象吗?

2 个答案:

答案 0 :(得分:1)

Counter类模板,它带有两个参数,即:此类模板由T1Count参数化。通过为这些参数提供参数,从此类模板生成类类型。

假设您传递给类模板的任何参数彼此不同,即:T1typeT2type不同或n与{{1}不同},然后mCounter<T1type, n>是不同的类型。因此,生成的对象由:

Counter<T2type, m>

也有不同的类型。因此,您无法定义常用(非模板化)类型来存储两个对象中的任何一个。

请注意,您的std::make_shared<Counter<T1type, n>>(); std::make_shared<Counter<T2type, m>>(); 类型别名将无法编译:

counterp

因为using counterp = std::shared_ptr<Counter>; 没有收到成为类型所需的两个模板参数。

但是,您可以定义别名模板

Counter

然后为template<typename T1, size_t Count> using counterp = std::shared_ptr<Counter<T1, Count>>; 提供它需要的两个模板参数:

couterp

再次注意counterp<T1type, n> myCounter1p = std::make_shared<Counter<T1type, n>>(); counterp<T2type, m> myCounter2p = std::make_shared<Counter<T2type, m>>(); counterp<T1type, n>可以是不同的类型。

答案 1 :(得分:0)

您可以使用auto

auto myCounter1p = std::make_shared<Counter<T1type, n>>;
auto myCounter2p = std::make_shared<Counter<T2type, m>>;

alias template

template<typename T1, size_t Count>
using counterp = std::shared_ptr <Counter<T1, Count>>;
...
counterp<T1type, n> myCounter1p = std::make_shared<Counter<T1type, n>>();
counterp<T2type, m> myCounter2p = std::make_shared<Counter<T2type, m>>();
相关问题