我可以使用模板功能参数C 更改模板类型

Can i change template class type using template function parameter c++

本文关键字:类型 功能 可以使 我可以 参数      更新时间:2023-10-16

我想将类的类型从t更改为new_t,是否可能?

template<class T,int count>
class obj_pool{
  public:
    template<class new_T>
    void Retypedef();
};

例如,为int obj_pool<int> pool创建的obj_pool,当用户调用 pool.Retypedef<double>()函数时,该池成为double的池。

no。

将来,当您写一个问题时,包括有关您要解决的基本问题的一些信息。然后,当您的意识解决方案是一个死胡同时,回答的人可以解决您的根本问题。

或询问有关该基本问题的新问题(通过问问题按钮)。

在您的示例中, Tnew_T是两个不同的参数。使用此模板可能看起来像:

obj_pool<int,3> x;
x.Retypedef<double>();   // <- passing different types for new_T
x.Retypedef<float>();    // <- does not change the type of x
x.Retypedef<int>();      // ..and of course you can use the same type for
                         // new_T as for T

如果您希望new_T总是与T相同,则可以简单地写:

template<class T,int count>
class obj_pool{
  public:
    void Retypedef();   // can use T 
};