gpt4 book ai didi

c++ - 模板类规范和继承

转载 作者:搜寻专家 更新时间:2023-10-31 01:25:18 24 4
gpt4 key购买 nike

template<typename T>
class CommonBase
{
};

template<typename T>
class Base : public CommonBase<T>
{
protected:
bool flag;
};

template<>
class Base<int> : public CommonBase<int>
{
Base() {flag = false;}
};

它会导致“flag 未在命名空间中声明”的错误。我哪里做错了?

最佳答案

它是类模板 Base 的显式特化。

你必须在类定义中包含数据成员标志

template<>
class Base<int> : public CommonBase<int>
{
protected:
bool flag;
public:
Base() {flag = false;}
};

来自 C++ 20 标准(13.8.3 显式特化)

  1. A member of an explicitly specialized class is not implicitly instantiated from the member declaration of the class template; instead, the member of the class template specialization shall itself be explicitly defined if its definition is required. ... The definition of an explicitly specialized class is unrelated to the definition of a generated specialization. That is, its members need not have the same names, types, etc. as the members of a generated specialization. Members of an explicitly specialized class template are defined in the same manner as members of normal classes, and not using the template<> syntax....

关于c++ - 模板类规范和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57056294/

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