我的类模板如下所示
计数器.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>>;
我理解它的那种微不足道的问题,对于模板和共享指针是新手,有太多东西需要你思考
所以基本上问题是你能像上面那样创建一个通用的共享指针类型并实例化对象吗?
最佳答案
Counter
是一个带有两个参数的类模板,即:此类模板由T1
参数化和 Count
.通过为这些参数提供参数,从此类模板生成类类型。
假设您传递给类模板的任何参数彼此不同,即:T1type
不同于T2type
或 n
不同于m
, 然后 Counter<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>
和 counterp<T2type, m>
可以是不同的类型。
关于c++ - 声明模板的共享指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48839936/