用于旧 gcc 的 C++ 模板在 clang++ 中导致 'shadows template parameter' 错误

标签 c++ templates clang++

我在 08 年左右使用 gcc 3.x 编写了这段代码。我现在正在尝试使用 clang 3.4 进行编译,但出现了一个我不理解的模板错误。这个想法是声明任意维度和精度的固定维度 vec 类型,然后基于这些定义 vecPair 类型。我不明白“a.convert()”中模板类型名 S 的使用是如何隐藏模板参数的;它旨在使用参数,而不是重新声明它。任何信息将不胜感激!

typedef unsigned int Uns;

template <typename T>
inline const T& min(const T& a, const T& b) {
  return a <= b ? a : b;
}

template <Uns N, typename T>
struct vec {

  T comp[N];

  template <Uns M, typename S>
  inline vec<M, S> convert() const {
    vec<M, S> converted;
    for (Uns i = 0; i < min(M, N); ++i) converted[i] = comp[i];
    for (Uns i = N; i < M; ++i) converted[i] = 0;
    return converted;
  }
};

template <Uns N, typename T>
struct vecPair {

  vec<N, T> a;
  vec<N, T> b;

  inline vecPair(const vec<N, T>& _a, const vec<N, T>& _b) : a(_a), b(_b) {}

  template <Uns M, typename S>
  inline vecPair<M, S> convert() const {
    vec<M, S> ca = a.convert<M, S>();
    vec<M, S> cb = b.convert<M, S>();
    return vecPair<M, S>(ca, cb);
  }
};

clang 3.4 给出以下输出:

$ clang++ -fsyntax-only vec-bug.cpp 
vec-bug.cpp:30:33: error: declaration of 'S' shadows template parameter
    vec<M, S> ca = a.convert<M, S>();
                                ^
vec-bug.cpp:28:29: note: template parameter is declared here
  template <Uns M, typename S>
                            ^
vec-bug.cpp:30:34: error: expected ';' at end of declaration
    vec<M, S> ca = a.convert<M, S>();
                                 ^
                                 ;
vec-bug.cpp:31:12: error: template argument for template type parameter must be a type
    vec<M, S> cb = b.convert<M, S>();
           ^
vec-bug.cpp:11:27: note: template parameter is declared here
template <Uns N, typename T>
                          ^
...

最佳答案

这似乎可行:

vec<M, S> ca = a.template convert<M, S>();
vec<M, S> cb = b.template convert<M, S>();

我认为 ab 具有依赖类型,因此您需要消除 convert 是模板的歧义。我不确定为什么 GCC 不介意。

更新:这似乎是一个known GCC bug.

关于用于旧 gcc 的 C++ 模板在 clang++ 中导致 'shadows template parameter' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22056659/

相关文章:

c++ - 我的初始化列表中的小错字导致无法形容的痛苦

c++ - C++ 中未初始化的变量行为

C++ 模板和以基类和子类作为模板参数的转换

c++ - 成员属性的 std::function 模板参数推导

c++ - C++ 中奇怪的后增量行为

c++ - 我们不能混合使用 g++ 和 clang++ 编译的对象(或库)吗?至少在 Mac 上?

c++ - 函数局部静态常量变量初始化语义

javascript - emberjs 中的嵌套路由而不使用资源导出

c++ - 使用 libc++ 输出 wchar_t

c++ - 如何在Makefile中添加#define?