防止const函数被调用非const对象

Prevent const function being called for non-const object

本文关键字:const 对象 调用 函数 防止      更新时间:2023-10-16

以下代码包含operator()的const和非const版本。它输出

non-const op,false
const op,true
const op,true
const op,true

即。如果S类型的对象是const,则称为const版本,如果提交的指针为const -lines // 2// 3// 4。现在,我希望// 2中的代码能够导致编译时间错误,即我希望const版本仅在const对象上call。显然,is_const_v<decltype(*this)>上的static_assert将不起作用。还有其他想法吗?
我知道,很容易将一个非const变量投放到一个const。但这会使滥用至少很明显。

#include <iostream>
#include <type_traits>
struct S
{
    void
    operator()( int * )
    {
        std::cout << std::boolalpha
            << "Non-const op, "
            << std::is_const_v<typename std::remove_reference_t<decltype(*this)> > << 'n';
    }
    void
    operator()( int const * ) const
    {
        std::cout << std::boolalpha
            << "Const op, "
            << std::is_const_v<typename std::remove_reference_t<decltype(*this)> > << 'n';
    }
};
int main()
{
    S         s1;
    S const   s2;
    int       i1= 0;
    int const i2= 1;
    s1( &i1 ); // 1
    s1( &i2 ); // 2
    s2( &i1 ); // 3
    s2( &i2 ); // 4
}

编辑
我的问题背后的原因如下。我正在存储提交的指针。这需要抛弃提交的指针的构造。现在,我想防止错误修改const数据。

您可以明确删除以下版本

void operator()( int const * ) = delete;

禁止

s1( &i2 ); // 2

void operator()( int * ) const = delete;

禁止

s2( &i1 ); // 3

如果我们将this作为显式参数(虚构语法(,请让我们看看它将如何工作

void call(S* this, int*) {
    // Wha? we clearly know `S*` is not const
    std::is_const_v<typename std::remove_reference_t<decltype(*this)> >
}
void call(S const* this, int const*) {
    // same
    std::is_const_v<typename std::remove_reference_t<decltype(*this)> >
}

soluton将是删除参数之间具有不同constness的函数:

void call(S* this, int*) {}
void call(S const* this, int const*) {}
void call(S* this, int const*) = delete;
void call(S const* this, int*) = delete;

现在可以使用成员函数来完成相同的操作:

struct S {
    void operator()(int*) {}
    void operator()(int const*) const {}
    void operator()(int const*) = delete;
    void operator()(int*) const = delete;
};

您可以通过删除采用const int*的版本来防止调用该功能。例如:

#include <iostream>
struct S {
    void foo(int*) {
        std::cout << "Calling foo(int*)n"; 
    }
    void foo(int const*) const {
        std::cout << "Calling foo(int const*)n"; 
    }
    void foo(int const*) = delete; 
};
int main() {
    S s1;
    S const s2;
    int i1;
    int const i2;
    s1.foo(&i1); // This compiles fine (both mutable)
    s2.foo(&i2); // This compiles fine too (both const)
    s2.foo(&i1); // This also compiles (s2 const, i1 mutable)
    s1.foo(&i2); // This fails as intended (s1 mutable, i2 const)
}