c++ - 模板类中定义的常量

标签 c++ templates g++ template-classes

<分区>

Possible Duplicate:
GCC problem : using a member of a base class that depends on a template argument

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

例如,gcc 说

test.h:18: error: ‘theconstant’ was not declared in this scope

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

#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 行的编译器无法确定您不会以该常量根本不存在的方式专门化 base<>。

关于c++ - 模板类中定义的常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11285732/

相关文章:

c++ - sizeof(std::list<T>) 可以因不同类型的 T 而有所不同吗?

C++ std::push_heap 破坏堆/不尊重比较器

c++ - Microsoft Visual C++ 的两阶段模板实例化的 "broken"究竟是什么?

c++ - 为什么指针类型转换不适用于模板非类型参数

c++ - 不能在类范围内使用 `static_assert` 和 `sizeof`(但方法范围没问题)

gcc - 生成文件中的 CC?= 是什么意思?

makefile - 在 Makefile 中使用 Clang++ 代替 G++

c++ - GTKmm 简单例子编译报错

c++ - 如何在从模板类继承时应用 move 语义

c++ - 如何从迷宫 ASCII 文本文件中创建动态分配的二维数组?