This question already has answers here:
Where and why do I have to put the “template” and “typename” keywords?
                                
                                    (6个答案)
                                
                        
                                在10个月前关闭。
            
                    
我发现这篇文章:
https://tristanbrindle.com/posts/beware-copies-initializer-list
我对部分所提供的代码有疑问:

第一:
我认为这是关于依赖名称的,但我不确定这部分的目的是什么:

 template <typename T>
    typename instance_counter<T>::counter instance_counter<T>::icounter{};


第二个:

template <typename T>
struct counted : T, private instance_counter<T>
{
    using T::T;
};


有人可以给我解释一下这些代码吗?

最佳答案

有人可以给我解释一下这些代码吗?


template <typename T>
typename instance_counter<T>::counter instance_counter<T>::icounter{};


这是在instance_counter模板中声明的静态变量的初始化(请参阅博客文章中的static struct counter { /* ... */ } icounter;)。有关静态数据成员的初始化的更多信息,请参见this thread。该定义引用模板的嵌套名称(counter),并且编译器默认将其视为值的名称,而不是类型。要更改此默认解释,您需要在typename之前添加。有关详细信息,请参见this thread

template <typename T>
struct counted : T, private instance_counter<T>
{
    using T::T;
};


在这里,模板countedT公开继承(public的默认继承是struct),从instance_counter<T>私有继承。公共继承部分与using T::T(会带来T的所有ctor重载)一起用于提供与实例化模板的类相同的接口(例如,帖子中的string)。私有继承部分表示是在术语中实现的,并确保为新实例化的类类型引入instance_counter机制,并在析构函数中生成输出。

07-24 09:44
查看更多