模板类中定义的常量

Constants defined in template classes

本文关键字:常量 定义      更新时间:2023-10-16

可能的重复项:
GCC 问题:使用依赖于模板参数的基类的成员

我以为我对C++很熟悉,但显然不够熟悉。
问题是,在模板类中定义常量时,可以在派生自该类的新类中使用该常量,但不能在派生自该类的新模板类中使用该常量。

例如,海湾合作委员会说

test.h:18:错误:"常量"未在此范围内声明

当我尝试编译这个(简化的)头文件时:

#pragma once
template <typename T> class base
{
  public:
    static const int theconstant = 42;
};
class derive1 : public base<size_t>
{
  public:
    derive1(int arg = theconstant) {}
};
template<typename T> class derive2 : public base<T>
{
  public:
    derive2(int arg = theconstant) {} // this is line 18
};

所以问题在于,一个类,derive1,编译得很好,但另一个类,derive2,这是一个模板专用,不能。
现在也许 gcc 的错误还不够清楚,但我不明白为什么 derive2 中的构造函数会与 derive1 中的构造函数具有不同的范围。
如果重要,这发生在头文件本身的编译期间,而不是在实例化类型为 derive2<type> 的对象时。

我也知道要更改什么才能使此编译,所以我并不是真的在寻找一行代码作为答案。我想了解为什么会这样!我尝试搜索网络,但显然我没有使用正确的搜索参数。

我很确定这会帮助你理解:

您的代码无法编译:

template<typename T> class derive2 : public base<T>
{
  public:
    derive2(int arg = theconstant) {} // this is line 18
};

原因如下:

template <> class base<size_t>
{
  public:
    static const int ha_idonthave_theconstant = 42;
};
derive2<size_t> impossible_isnt_it; 

专业化!!第 18 行的编译器无法确定您不会专门化基数<>就像这个常量根本不存在一样。

尝试

template<typename T> class derive2 : public base<T>
{
  public:
    derive2(int arg = base<T>::theconstant) {} // this is line 18
};

基本上,您已经为"theconstant"指定了不完整的范围。