【问题标题】:Template template parameter errors in MSVC, but not Clang. Why?MSVC 中的模板模板参数错误,但 Clang 中没有。为什么?
【发布时间】:2013-09-05 19:05:49
【问题描述】:

我编写了这段代码来帮助我根据一些谓词对引用集合的索引进行排序:

#include <algorithm>
#include <functional>
#include <vector>

template<template<class> class Pred = std::less>
struct element_is_pred
{
    template<class C>
    struct type : private Pred<typename C::value_type>
    {
        typedef Pred<typename C::value_type> Base;
        C const *c;
        type(C const &c, Base const &pred = Base())
            : Base(pred), c(&c) { }
        bool operator()(
            typename C::size_type const i,
            typename C::size_type const j) const
        { return this->Base::operator()((*c)[i], (*c)[j]); }
    };
};

template<template<class> class P, class C>
static element_is_pred<P>::template type<C const> element_is(
    C const &c,
    P<typename C::value_type> const &pred = P<typename C::value_type>())
{
    return typename element_is_pred<P>::template type<C const>(c, pred);
}

我是这样使用它的:

int main()
{
    std::vector<size_t> temp;
    std::vector<size_t> indices;
    indices.push_back(0);
    std::stable_sort(
        indices.begin(),
        indices.end(),
        element_is<std::less>(temp));
}

当我用 Clang 3.2 编译它时:

clang++ -fsyntax-only Test.cpp

它编译得很好。

但是当我尝试用 Visual C++ 2013 编译它时,我得到了大量的错误,例如:

test.cpp(23) : warning C4346: 'element_is_pred<Pred>::type<const C>' : dependent name is not a type
        prefix with 'typename' to indicate a type
test.cpp(23) : error C2146: syntax error : missing ';' before identifier 'element_is'
test.cpp(23) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

哪个编译器是正确的?
编写代码的正确方法是什么?

【问题讨论】:

    标签: c++ visual-c++ clang typename template-templates


    【解决方案1】:

    GCC 给出以下错误:

    error: need 'typename' before 'element_is_pred<Pred>::type<const C>' because 'element_is_pred<Pred>' is a dependent scope
    

    按照这个建议,我可以通过添加 typename 来让程序在 GCC 上构建:

    static typename element_is_pred<P>::template type<C const> element_is(
           ^^^^^^^^
    

    Clang 也允许修改版本。

    【讨论】:

    • +1 出于某种原因,这在我的原始代码中不起作用,但它在这里起作用。这将引导我朝着正确的方向前进,谢谢。
    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 2011-10-01
    • 2021-10-07
    • 1970-01-01
    • 2021-02-07
    相关资源
    最近更新 更多