c++ 声明中的 ::type 是什么意思

What does ::type in c++ declaration mean?

本文关键字:type 意思 是什么 声明 c++      更新时间:2023-10-16

以下代码取自cpp-netlib,但我在其他地方看到了类似的声明。

template <class Handler>
struct server : server_base<tags::http_server, Handler>::type 
{
    typedef typename server_base<tags::http_server, Handler>::type server_base;
    typedef server_options<tags::http_server, Handler> options;
    explicit server(options const &options) : server_base(options) {}
};

请有人解释一下在声明中使用::type的意义。在搜索框中使用"type"一词进行搜索会抛出太多不相关的结果,无法找到答案。

蒂亚

这是一种解决方法,因为 C++98(以及 C++03)不允许模板 typedefs。如果你查看server_base类,你会看到一个名为 typetypedef,其类型取决于server_base的模板参数。仅供参考,在 C++11 中,您可以使用别名声明。请参阅C++模板类型定义

它可能是定义某种类型的模板化类/结构中的 typedef。为了查看它的真实情况sever_base模板定义中的外观,或者如果使用Visual Studio,只需将鼠标悬停在类型上 - 它应该将基础类型显示为工具提示

大多数时候,它是一个简化访问/公开内部类型的工具。无需编写模板类的长声明,只需通过 ::type 访问该类型即可。这种方式广泛用于C++标准库中,例如std::integral_constant

#include <type_traits>
typedef std::integral_constant<int, 2> two_t;
two_t::type my_constant; // <--- simplified