模板类中定义的常量
Constants defined in template classes
可能的重复项:
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"指定了不完整的范围。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 我可以在运行时重新定义在 OpenCascade/OCCT 标头中定义的 c++ 静态常量吗?
- 在定义的函数中使用常量时出错
- 模板推导:为什么函数指针模板定义在常量和/或引用时不匹配?
- C++ 确保子类为常量提供自定义值
- 用矩阵将函数中的整数值替换定义的常量
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 将字符串文本常量定义为 char const* 和 wchar const*
- 为什么不建议使用宏符号常量定义一个固定长度的数组呢
- 我可以使用常量定义数组的长度,那么为什么 int d[b] 不起作用呢?
- 调用构造函数与将内联常量定义为默认参数
- 是否允许在常量定义的对象上丢弃 const 只要它没有实际被修改?
- 多个文件中的常量定义
- 常量定义和模板
- 如何在另一个命名空间中使用常量定义的外部
- 全局常量定义的顺序
- 将常量定义为函数会导致标头=坏主意
- 是一个宏,其变量总是用变量或常量定义