防止const函数被调用非const对象
Prevent const function being called for non-const object
以下代码包含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)
}
相关文章:
- 被解释为低级别const的const对象的地址
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- "this"指向的对象是否与 const 对象相同?
- 从 const 对象访问非 const 方法
- 将非 const 对象用于 const 参数
- 如何键入用于const对象的自定义io操纵器
- 哪个 const 与哪个引用将更改参数并创建一个 const 对象?
- 无法在返回中转换 const 对象
- 接受对 const 对象的引用但没有 r 值的函数
- 当我调用 main 中使用 const 对象的 const 函数时,不断出现错误
- 在 const 对象上调用非 const 函数
- 正确的方法通过巨大的const对象的向量
- 如何重载 const 对象的 [],以便值赋值不会导致编译错误
- 相互引用的 Const 对象
- 析构函数是否可以在 const 对象上调用非 const 函数
- decltype 不会推断 const 对象的 const 成员
- 防止const函数被调用非const对象
- constexpr引用非const对象