使用嵌套在模板参数中的typename

Col*_*nee 5 c++ templates nested typename

这是一个满口的,所以这里有一段代码作为例子:

template<typename T>
void foo(const T& a, typename T::value_type::value_type b) { }

std::vector<std::vector<int>> vec;
foo(vec, 4); // Error, can't specialize function template
Run Code Online (Sandbox Code Playgroud)

这使用gcc编译并正确运行.由于上面评论的原因,它无法使用Visual Studio 2010进行编译.但是,如果最终value_type的前缀是template关键字,它将编译并正确运行.我有几个猜测为什么,但找不到标准的相关部分.

template<typename T>
void foo(const T& a, typename T::value_type::template value_type b) { }

std::vector<std::vector<int>> vec;
foo(vec, 4); // Compiles and runs correctly with Visual Studio 2010
Run Code Online (Sandbox Code Playgroud)

我知道上面的用法template是一个Visual Studio扩展,但是标准对于使用这样的类型有什么看法呢?gcc对代码的接受是否也是一个扩展,或者这是Visual Studio的一部分吗?

ild*_*arn 4

这绝对是 VC++ 2010 的一个缺陷——std::vector<int>::value_type它是一个类型,而不是一个模板,并且不应该被这样修饰。事实上,在这种情况下使用该语法应该会导致编译器错误。

支持证据是以下内容确实可以编译(因为它应该):

#include <vector>

template<typename T>
void foo(T const& a)
{
    typename T::value_type::value_type bar = a.at(0).at(0);
}

int main()
{
    std::vector<std::vector<int>> vec;
    foo(vec);
}
Run Code Online (Sandbox Code Playgroud)

并且以下内容不会(因为它不应该):

template<typename T>
void foo(T const& a)
{
    typename T::value_type::template value_type bar = a.at(0).at(0);
}
Run Code Online (Sandbox Code Playgroud)

产生的错误是

错误C2903::'value_type'符号既不是类模板也不是函数模板

我建议在MS Connect上打开错误报告并将链接发布回此处,以便我们对其进行投票。