【问题标题】:c++11 how to convert legacy class to templatec++11如何将遗留类转换为模板
【发布时间】:2021-11-21 03:06:14
【问题描述】:

我有一个遗留类,例如:

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 转换为模板类,而无需编辑所有已使用的地方?

【问题讨论】:

  • 在 C++17 中,CTAD 允许在某些地方省略 &lt;..&gt;
  • 当您对代码进行现代化改造时,您可能会使用using 而不是typedefusing Wrapper = WrapperT&lt;void*&gt;;

标签: c++ c++11 templates typesafe


【解决方案1】:

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

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

using Wrapper = WrapperT<void*>;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 2021-06-10
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多