当前位置: 首页 > 知识库问答 >
问题:

带有常量引用的std::remove_const

籍英叡
2023-03-14

为什么std::remove_const不将const t&转换为t&?这个诚然相当做作的例子说明了我的问题:

#include <type_traits>

int main()
{
    int a = 42;
    std::remove_const<const int&>::type b(a);

    // This assertion fails
    static_assert(
        !std::is_same<decltype(b), const int&>::value,
        "Why did remove_const not remove const?"
    );

    return 0;
}

上面的情况很容易修复,所以对于上下文,想象一下下面的情况:

#include <iostream>

template <typename T>
struct Selector
{
    constexpr static const char* value = "default";
};

template <typename T>
struct Selector<T&>
{
    constexpr static const char* value = "reference";
};

template <typename T>
struct Selector<const T&>
{
    constexpr static const char* value = "constref";
};

int main()
{
    std::cout
        << Selector<typename std::remove_const<const int&>::type>::value
        << std::endl;

    return 0;
}

在上面的示例中,我希望显示reference,而不是constref

共有1个答案

蒲功
2023-03-14

std::remove_const删除顶级const-限定。在const t&(相当于t const&)中,限定不是顶级的:事实上,它并不应用于引用本身(这将是没有意义的,因为引用根据定义是不可变的),而是应用于被引用的类型。

C++11标准第20.9.7.1段中的表52针对std::remove_const:

成员typedef类型应命名与t相同的类型,但删除了任何顶级const-qualifier。[示例:remove_const ::type 计算结果为volatile int,而remove_const ::type 计算结果为const int*。-结尾示例]

为了删除const,您必须首先应用std::remove_reference,然后应用std::remove_const,然后(如果需要)应用std::add_lvalue_reference(或适合您的任何情况)。

注意:正如Xeo在注释中提到的,您可以考虑使用一个别名模板(如inqualified)来执行前两个步骤,即去掉引用,然后去掉const-(和volatile-)限定。

 类似资料:
  • 两者之间有实际区别吗 和 ? 看起来包含常量元素的非常量数组仍然无法交换,赋值运算符也不起作用<我什么时候应该选择一个而不是另一个?

  • 错误:无法将类型为“std::_bit_reference&”的非常量lvalue引用绑定到类型为“std::vector::reference”{aka“std::_bit_reference”}的rvalue 因此,它抱怨,因为只有第二个参数是rvalue

  • 我有以下课程 我在下面的代码中使用 由此产生的行为对我来说是可以理解的。在第一次调用中,构造一个小部件,然后调用移动构造函数,并在临时小部件上调用析构函数。 第二个调用也执行相同的操作,除了调用move赋值运算符而不是move构造函数。离开main方法,析构函数在<code>c<code>上调用。 现在是有趣的部分: 如果我省略了对< code>std::move的调用,第一种情况会停止工作,只导

  • 我试图弄清楚为什么Lettuce会给我带来这么多问题,而我正在运行我的性能测试,将它与Jedis进行比较。 我使用spring-data-redis1.8.11.release,并为通过Redistemplate访问redis的接口创建了自定义代理bean。Redis运行在AWS中,我使用AWS提供的集群配置endpoint作为节点,它有3个主节点和3个从节点。在性能测试过程中没有发生任何特殊情况

  • 我想定制一个EditText,它应该像下图中那样具有“常量”,这样我就可以得到分钟和秒。(数字接口无关)。

  • 假设我有一个函数,它接受<code>std::function</code>: 我应该通过常量引用传递<code>x</code>吗 这个问题的答案是否会根据函数的作用而变化?例如,如果它是一个类成员函数或构造函数,它将 存储或初始化为成员变量。