c++ - MSVC 中的模板模板参数错误,但不是 Clang。为什么?

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

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

#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

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

最佳答案

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 也允许修改版本。

关于c++ - MSVC 中的模板模板参数错误,但不是 Clang。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18644049/

相关文章:

ios - Clang GCC 扩展 - 括号中的 block 返回一个值

c++ - 为什么 boost::mutex 使用原子操作和事件而不是临界区

c++ - C++ 中是否有标准的循环迭代器

c++ - 新[],删除[]复杂度

visual-c++ - 如何识别PreTranslateMessage中的鼠标点击事件?

c++ - Clang 为直觉上应该等效的表达式提供非常不同的性能

c++ - 什么是对象切片?

c++ - 添加 #include <boost/thread/mutex.hpp> 会破坏我的 ActiveX 控件吗?

c++ - 如何使用 COM 从 win32 应用程序处理 Excel 2007 和 Excel 2003(Excel 图表)?

ios - 找不到 Xcode Clang 错误文件