c++ - 使用不完整类型 void 的模板类

标签 c++ templates

我有以下模板类:

template <typename T>
class myClass
{
public:
    // Many methods...
protected:
private:
    T attribute
    // Other attributes.
};

实例化 myClass<void> 类型的对象不工作,因为 void attribute . 你能给我一些提示,让我能够使用 myClass<void> 类型的对象吗?没有专门化整个类(class)。由于它有许多依赖于类型 T 的成员函数,因此对其进行特殊化会导致代码重复。

最佳答案

创建一个包含属性的模板化基类,将其专门化为 void 并从中继承:

namespace detail //Warn end user that he should not use stuff from here
{
    template <typename T>
    struct myClass_base
    {
        T attribute;
    };

    template <>
    struct myClass_base<void>
    {}; //No attribute at all
}

template <typename T>
class myClass: private detail::myClass_base<T>
{
    //rest of definition
};

这会使 myClass 在实例化类型为 void 时缺少 attribute 字段

关于c++ - 使用不完整类型 void 的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37734490/

相关文章:

c++ - CLion 编译时卡住

c++ - 什么是三重检查锁定模式

c++ - 为什么模板只能在头文件中实现?

c++ - 在 C++ 中向下转换模板类型名称对象

c++ - ccls 安装在 neovim 中但无法正常工作

c++ - 如何正确添加状态栏?

c++ - 模板继承和可变参数

c++ - 使用 g++ 和 clang++ 调用 Integral 模板成员函数时出错

c++ - 可以从硬编码整数常量中删除 "LL"并替换为 "static_cast<uint64_t>(...)"吗?

C++ typedef 到可变参数模板参数