C++ difference of keywords 'typename' and 'class' in templates

本文详细解释了在C++中模板类型(typename)和类(class)之间的区别,包括它们在不同情况下的应用,如依赖类型、模板模板等,并提供了实例说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

typename and class are interchangeable in the basic case of specifying a template:

template
class Foo
{
};

and

template
class Foo
{
};

are equivalent.

Having said that, there are specific cases where there is a difference between typename and class.

The first one is in the case of dependent types. typename is used to declare when you are referencing a nested type that depends on another template parameter, such as the typedef in this example:

template
class Foo
{
typedef typename param_t::baz sub_t;
};

The second one you actually show in your question, though you might not realize it:

template < template < typename, typename > class Container, typename Type >

When specifying a template template, the class keyword MUST be used as above – it is not interchangeable with typename in this case.

You also must use class when explicitly instantiating a template:

template class Foo;

I’m sure that there are other cases that I’ve missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值