【问题标题】:Add const to reference将 const 添加到引用
【发布时间】:2018-10-11 23:13:18
【问题描述】:

我想将 const 添加到 typedef const A B; 的引用类型中。

不知何故,它不起作用。这在 c++ 中是不可能的吗?

测试:

#include <type_traits>
typedef int& A;
typedef const A B;  // <-- Add const
// typedef std::add_const<A>::type B;  // also doesn't work.
static_assert(std::is_const<typename std::remove_reference<
        B>::type>::value, "is const");
int main() {
    return 0;
}

编译错误:

add2.cpp:5:1: error: static assertion failed: is const
 static_assert(std::is_const<typename std::remove_reference<
 ^~~~~~~~~~~~~

【问题讨论】:

    标签: c++ templates constants


    【解决方案1】:

    不幸的是,std::add_const&lt;T&gt; 并没有按照您的想法做参考。 将const 添加到引用的方法是这样的:

        using in_type = double&;
    
        using out_type = std::add_lvalue_reference_t<std::add_const_t<std::remove_reference_t<in_type>>>;
    
        static_assert( std::is_same<out_type, double const&>{} , "!");
    

    【讨论】:

      【解决方案2】:

      不知何故,它不起作用。这在 c++ 中是不可能的吗?

      不是你的方式。 typedef 不像预处理器宏那样工作。

      typedef int& A;
      typedef const A B;
      

      不会翻译成

      typedef int& A;
      typedef const int& B;
      

      中的const
      typedef const A B;
      

      适用于A,而不是Aint 部分。由于引用在 C++ 中是不可变的,因此从类型的角度来看,const AA 相同。


      你可以使用:

      typedef int const& B;
      

      如果你想从A 派生它,你可以使用:

      using B = typename std::remove_reference<A>::type const&;
      

      如果您能够使用 C++14 或更高版本,您可以将其简化为:

      using B = std::remove_reference_t<A> const&;
      

      【讨论】:

      • West const 又输了。
      • @Yakk,这是我第一次听到这种表达方式。谢谢你。
      猜你喜欢
      • 2019-05-10
      • 2021-02-16
      • 1970-01-01
      • 2018-10-03
      • 2017-03-12
      • 2021-10-18
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      相关资源
      最近更新 更多