首页 > 解决方案 > 可以在不使用 decltype 的情况下推断先前定义的 extern 变量的类型吗

问题描述

// header

int extern has_a_type; // (1) extern declaration

// implementation

decltype(has_a_type)   // (2) unnecessarily verbose type inference code
has_a_type;            // (3) definition

我知道我可以使用decltype,所以在定义(3)(并可能初始化)它时,我实际上不必键入(甚至在某种程度上知道)extern 声明的(1)变量的类型。然而decltype,迫使我写出变量的名称(可能是完全限定的和长的)两次(2)。

我怎样才能避免写两次?类似的东西auto has_a_type;(当然,这行不通)。

标签: c++c++11externdecltype

解决方案


你不能——开玩笑,因为没有人说服标准委员会相信能够写作的好处

int extern has_a_type;
auto has_a_type;

尽管它易于处理。结果可能是

decltype(auto) has_a_type;

decltype(has_a_type)为了消除初始化器的类型推导歧义,这是必要的,然后,不幸的是,我们与已经可用的重复性相距不远。


推荐阅读