【问题标题】:No difference if "typename" is used in template specialization如果在模板特化中使用“typename”没有区别
【发布时间】:2016-09-15 13:13:37
【问题描述】:

我有一个简单的模板,比如

template <typename a, typename b, typename c> 
class myclass
{

};

我意识到我可以通过以下两种方式专门化模板:

template <typename a, typename b>
class myclass<a, b, int> 
{

};

template <typename a, typename b>
class myclass<a, b, typename int> 
{

};

为什么“typename int”和“int”没有区别?

【问题讨论】:

  • 你肯定在使用 msvc。
  • “我意识到我可以通过以下两种方式专门化模板:” gcc 和 clang 确实不同意。
  • 应该不起作用。 And nope, doesn't work。你的编译器有问题。
  • 所以正式的方式应该是“int”而不是“typename int”?

标签: c++ templates


【解决方案1】:

有,一定是 Visual Studio 的错误。因为 Visual Studio 没有实现两阶段名称查找,并且无法确定什么是依赖类型,所以它允许您编译它而不会出错。但是,使用 gcc 编译时,会出现以下错误:

main.cpp:11:33: error: template argument 3 is invalid
class myclass<a, b, typename int>
                    ^

但是当将它与依赖名称一起使用时,typename 关键字必须出现以告诉编译器它不是值或类型以外的其他东西。事实上,typename 关键字只能在真正需要时出现。

但是,在某些上下文中,编译器已经知道表达式必须屈服于类型,例如继承。如果您尝试将typename 放在从属名称的前面,您将收到错误消息。看看这段代码:

template <typename A>
struct MyType : typename std::decay<A>::type {};

这会导致该错误:

main.cpp:6:17: error: keyword 'typename' not allowed in this context (the base class is implicitly a type)
 struct MyType : typename std::decay<A>::type {};
                 ^

仅当模板中有不明确的语句时,编译器才需要这些关键字。否则不能放这些关键词。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-22
    • 2011-05-30
    • 2011-01-02
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多