【问题标题】:What am I doing wrong here? Or is this a clang++ bug?我在这里做错了什么?或者这是一个clang++错误?
【发布时间】:2015-05-18 23:24:03
【问题描述】:

以下代码在我的 Mac 上编译失败

#include <iostream>
#include <array>

template <typename T, unsigned int N>
using Vector = std::array<T, N>;

template <typename T, unsigned int N>
T dot(const Vector<T, N> &l, const Vector<T, N> &r) {
    T result{0};
    for (auto i = 0; i < N; ++i) {
        result += l[i] * r[i];
    }
    return result;
}

using Vector3f = Vector<float, 3>;

int main(int argc, const char * argv[]) {
    Vector3f u{1.0f, 2.0f, 3.0f};
    Vector3f v{6.0f, 5.0f, 4.0f};

    std::cout << dot(u, v) << std::endl;

    return 0;
}

这是我从终端编译的方式:

clang++ -std=c++11 -stdlib=libc++ repro.cpp -o repro

这是我得到的错误:

repro.cpp:24:18: error: no matching function for call to 'dot'
    std::cout << dot(u, v) << std::endl;
                 ^~~
repro.cpp:10:3: note: candidate template ignored: substitution failure [with T = float]: deduced non-type template
      argument does not have the same type as the its corresponding template parameter
      ('unsigned long' vs 'unsigned int')
T dot(const Vector<T, N> &l, const Vector<T, N> &r) {
  ^
1 error generated.

代码在 Visual Studio 2015 Preview 中编译良好。

当我用以下方式替换点调用时,它可以从终端正常编译:

std::cout << dot<float, 3>(u, v) << std::endl;

P.S.:我正在使用的 clang++ 版本: 铿锵++--版本 Apple LLVM 6.0 版(clang-600.0.57)(基于 LLVM 3.5svn)

【问题讨论】:

    标签: c++ macos clang++


    【解决方案1】:

    unsigned int 的所有实例替换为std::size_tstd::array 类模板声明为。

    template< class T, std::size_t N > struct array;
    

    模板实参推演过程中,如果非类型模板形参与对应实参不匹配,则推演失败。在您的系统上,std::size_t 恰好是别名 long unsigned int 将代码更改为以下内容应该可以:

    template <typename T, std::size_t N> // <--
    using Vector = std::array<T, N>;
    
    template <typename T, std::size_t N> // <--
    T dot(const Vector<T, N> &l, const Vector<T, N> &r);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 2013-06-28
      • 2023-01-19
      相关资源
      最近更新 更多