为什么你有时需要写 `typename T` 而不仅仅是 `T`? [英] Why do you sometimes need to write `typename T` instead of just `T`?

查看:38
本文介绍了为什么你有时需要写 `typename T` 而不仅仅是 `T`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于 SFINAE 的维基百科文章并遇到以下代码示例:

I was reading the Wikipedia article on SFINAE and encountered following code sample:

struct Test 
{
    typedef int Type;
};

template < typename T > 
void f( typename T::Type ) {} // definition #1

template < typename T > 
void f( T ) {}                // definition #2

void foo()
{
    f< Test > ( 10 ); //call #1 

    f< int > ( 10 );  //call #2 without error thanks to SFINAE
}

现在我以前确实写过这样的代码,不知何故,我凭直觉知道我需要输入typename T"而不是T".但是,了解其背后的实际逻辑会很好.有人愿意解释吗?

Now I've actually written code like this before, and somehow intuitively I knew that I needed to type "typename T" instead of just "T". However, it would be nice to know the actual logic behind it. Anyone care to explain?

推荐答案

总的来说,C++ 的语法(从 C 继承而来)有一个技术缺陷:解析器必须知道某个东西是否命名了一个类型,否则它就不能't 解决某些歧义(例如,X * Y 是乘法,还是声明指向 X 类型对象的指针 Y?这一切都取决于 X 是否命名了类型...!-).typename形容词"可让您在需要时完全清楚和明确(正如另一个答案所提到的,当涉及模板参数时,这是典型的;-).

In general, C++'s syntax (inherited from C) has a technical defect: the parser MUST know whether something names a type, or not, otherwise it just can't solve certain ambiguities (e.g., is X * Y a multiplication, or the declaration of a pointer Y to objects of type X? it all depends on whether X names a type...!-). The typename "adjective" lets you make that perfectly clear and explicit when needed (which, as another answer mentions, is typical when template parameters are involved;-).

这篇关于为什么你有时需要写 `typename T` 而不仅仅是 `T`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆