gpt4 book ai didi

c++11 如何将遗留类转换为模板

转载 作者:行者123 更新时间:2023-12-02 16:06:02 24 4
gpt4 key购买 nike

我有一个像这样的遗留类:

class Wrapper{
public:
Wrapper(void*);
void* get();
};

我想创建一个类型安全的包装器,例如:

template<class T>
class Wrapper{
public:
Wrapper(T);
T get();
};

由于 C++11,这样的东西将无法工作:

template<class T = void*> //Here I would need <>
class Wrapper...

typedef Wrapper<void*> Wrapper; //This isn't allowed

有没有一种方法可以将 Wrapper 转换为模板类,而无需编辑所有已使用它的地方?

最佳答案

如果你不想在其他地方改变,你可以给你的模板类一个不同的名字(因为你甚至没有在第一时间使用它):

template<typename T>
class WrapperT
{
public:
WrapperT(T t) : _T(t) {}
T get() { return _T; }
private:
T _T;
};

using Wrapper = WrapperT<void*>;

如果您随后删除了 Wrapper 的所有用法,您可以重命名 WrapperT

关于c++11 如何将遗留类转换为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69372464/

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