以下代码包含的const版本和非const版本operator()。输出
非const运算,假
常量运算,真正的
常量运算,真正的
常量运算,真
即const版本被称为如果任一类型的对象S或是常量如果所提交的指针是常量-线// 2,// 3,// 4。现在,我希望代码// 2可以导致编译时错误,即,我希望const版本只能在const对象上调用。显然,static_assert开启is_const_v<decltype(*this)>不会起作用。还有其他想法吗?
我知道,将非常量变量转换为常量很容易。但这将使滥用至少显而易见。
#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
}
Run Code Online (Sandbox Code Playgroud)
编辑
我的问题背后的原因如下。我正在存储提交的指针。这需要丢弃提交的指针的常量性。现在,我想防止const数据被错误地修改。
您可以明确删除以下版本
void operator()( int const * ) = delete;
Run Code Online (Sandbox Code Playgroud)
禁止
s1( &i2 ); // 2
Run Code Online (Sandbox Code Playgroud)
和
void operator()( int * ) const = delete;
Run Code Online (Sandbox Code Playgroud)
禁止
s2( &i1 ); // 3
Run Code Online (Sandbox Code Playgroud)