简体   繁体   English

模板外的typename

[英]typename outside of template

This in VS2010sp1 doesn't compile (it does compile with gcc 4.6 though): 这在VS2010sp1中没有编译(虽然它使用gcc 4.6进行编译):

template<class T>
struct Upcast;

template<>
struct Upcast<signed char>
{
    typedef signed short type;
};

template<>
struct Upcast<char>
{
    typedef typename std::conditional<std::is_signed<char>::value,short, unsigned short>::type type;
};

int main()
{
    Upcast<char>::type a;
    return 0;
}

Error from VS: 来自VS的错误:

Error   1   error C2899: typename cannot be used outside a template declaration

Which team is right? 哪支队伍是对的? VS or gcc? VS还是gcc?

VS is right on C++03. VS在C ++ 03上是正确的。 GCC is right on C++0x. GCC在C ++ 0x上是正确的。

Now it may be sensible for GCC to also allow this in C++03 mode (there are many things real compilers don't diagnose in C++03 mode that are actually only valid in C++0x), and it may as-well sensible for VS to reject it in C++03 mode. 现在,GCC也可以在C ++ 03模式中允许这种情况(实际编译器在C ++ 03模式中没有很多东西实际上只在C ++ 0x中有效),它可能是-well对于在C ++ 03模式下拒绝它是明智的。

It doesn't matter anymore whether or not a use of typename QualifiedName happens in a template or not, in C++0x. 在C ++ 0x中,是否在模板中使用typename QualifiedName并不重要。 That is, the following is perfectly legal for C++0x: 也就是说,以下内容对于C ++ 0x来说是完全合法的:

#include<vector>

int main() {
  typename std::vector<int> v;
}

In C++03, typename could only be used inside of a template. 在C ++ 03中, typename只能在模板中使用。 And the explicit specialization in your code is not a template. 并且代码中的显式特化不是模板。 There are no template<typename T ...> clauses (all parameters in your code are fixed). 没有template<typename T ...>子句(代码中的所有参数都是固定的)。

As per C++03, typename and template keywords are not allowed anywhere outside a template, including explicit (full) template specializations. 根据C ++ 03, template外的任何地方都不允许使用typenametemplate关键字,包括显式(完整)模板特化。 So MSVC++ is correct as per C++03 因此,根据C ++ 03,MSVC ++是正确的

As per C++0x this code is correct. 根据C ++ 0x,这段代码是正确的。

In this particular case it would seem that VS2010 is right in rejecting the code: 在这种特殊情况下,似乎VS2010拒绝代码是正确的:

14.6/5 14.6 / 5

The keyword typename shall be applied only to qualified names, but those names need not be dependent. 关键字typename只能应用于限定名称,但这些名称不必相关。 The keyword typename shall be used only in contexts in which dependent names can be used. 关键字typename只能在可以使用从属名称的上下文中使用。 This includes template declarations and definitions but excludes explicit specialization declarations and explicit instantiation declarations. 这包括模板声明和定义,但不包括显式特化声明和显式实例化声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM