c++ - 在编译时确定这是否是只读的

标签 c++ c++11 readonly static-assert

是否可以在编译时判断this指针是否为const指针? 我想实现这样的目标:

class Foo
{
    Foo() 
    { 
        static_assert( is this read only?, "works only on read only objects"); 
    }
}

这样的事情可能吗?

编辑

我为什么要实现这个目标?我有一个类,它接受一个指向只读表的指针。我想要一个构造函数来分配这个指针,但前提是该对象是只读的,因为应该禁止编辑表。

class Foo
{
public:
    template <std::size_t N>
    explicit constexpr Foo(const int(&table)[N])
    : m_table(table),
      m_size(N)
    {
    }

    Foo(const Foo& rhs)
    : m_table(new int[rhs.size()]),
      m_size(rhs.size())
    {
         // copy rhs.m_table into m_table
    }


    std::size_t size() const                    { return m_size; }
    const int& row(std::size_t i) const         { assert(m_size > i);  return m_table[i]; }
    int& row(std::size_t i)                     { assert(m_size > i);  return m_table[i]; }

private:
    int* m_table  = nullptr;
    std::size_t m_size  = 0;
};

如果 static_assert 是可能的,上面的代码将是安全的。我可以这样使用:

constexpr int table[10];
constexpr Foo foo(table);  // ok not an error
auto& a = foo.row(0);      // error
const auto& b = foo.row(0) // ok 

Foo bar(foo);
auto& b = bar.row(0);      // ok 

Foo foobar(table)          // static_assert if possible

最佳答案

更新问题后:

所以你想要的是一个只“返回”const 对象的构造函数。

虽然有针对此功能的提案,但它从未成为标准:[N0798]

一个简单的解决方案是使用 Mohamad Elghawi 描述的概念.

另一种变体可能是摆脱所有非常量函数,这样对象本身就是const,即使它不是真的。


旧答案:

是的,你可以使用这样的东西:

class Foo
{
public:
    Foo()
    {
    }

    void doSomething()
    {
        static_assert(std::is_const<std::remove_pointer_t<decltype(this)>>::value, "works only on read only objects");
    }

    void doSomethingConst() const
    {
        static_assert(std::is_const<std::remove_pointer_t<decltype(this)>>::value, "works only on read only objects");
    }

};

DEMO

我仍然不明白这有什么用,因为如果这是 const,对它或它的成员的任何写访问也会在编译时失败...

关于c++ - 在编译时确定这是否是只读的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746085/

相关文章:

python - 如何在 Django 表单中创建用户无法编辑的只读字段?

sql - Heroku Postgres 数据库的只读权限

html - knockout attr 与 'readonly' 和 'disabled' 等属性的绑定(bind)

c++ - 如何在基于范围的 for 中使用多个容器?

c++ - 在结构内创建绑定(bind)到 io_service 的线程

c++ - 错误: assignment of member in read-only object

c++ - 数组和右值(作为参数)

c++ - 为什么 g++5 在自动类型推导中推导对象而不是 initializer_list

c - 有什么干净的方法可以让 OpenMP pragmas 与宏一起工作?

c++ - 我什么时候应该在 C++ 中重用变量名