【问题标题】:What does ::type in c++ declaration mean?c++ 声明中的 ::type 是什么意思?
【发布时间】:2015-03-16 08:02:22
【问题描述】:

以下代码取自 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 的意义。在搜索框中使用“类型”一词进行搜索会抛出太多不相关的结果,无法找到答案。

TIA

【问题讨论】:

    标签: c++ templates types keyword


    【解决方案1】:

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

    【讨论】:

    • 没听说过C++99,只有C++98和C99
    • @LưuVĩnhPhúc :) 是的,对不起,我把 C99 弄混了
    【解决方案2】:

    它可能是定义某种类型的模板化类/结构中的 typedef。为了查看它的真正含义,要么查看 sever_base 模板定义,要么如果使用 Visual Studio,只需将鼠标悬停在类型上 - 它应该将底层类型显示为工具提示

    【讨论】:

    • 投反对票的原因?
    • 我不知道谁投了反对票,因为这问题的正确答案。
    • 我没有投反对票。但并不是每个人都使用 Visual Studio,而且这个问题没有被标记为 Visual Studio 问题。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      相关资源
      最近更新 更多