With decltype
and std::is_const
变量的常量可以从外部检测到。但是一个对象是否也有可能知道它自己的常量呢?用法应该是这样的:
#include <type_traits>
#include <iostream>
#include <ios>
struct Test
{
Test() {}
bool print() const
{
// does not work as is explained in https://stackoverflow.com/q/9890218/819272
return std::is_const<decltype(*this)>::value; // <--- what will work??
}
};
int main()
{
Test t;
const Test s;
// external constness test
std::cout << std::boolalpha << std::is_const<decltype(t)>::value << "\n";
std::cout << std::boolalpha << std::is_const<decltype(s)>::value << "\n";
// internal constness test
std::cout << std::boolalpha << t.print() << "\n";
std::cout << std::boolalpha << s.print() << "\n"; // <--- false??
}
输出开启生活工作空间这有可能吗?
动机:我希望能够检测 const 成员函数是在 const 对象上调用还是来自非 const 对象。该物体可以例如代表一个缓存,成员代表一个视图。如果缓存是常量的,则可以使用优化的绘制例程,而如果基础数据是非常量的,则绘制例程将需要定期检查数据是否已刷新。
NOTE: 相关的question询问如何打破 const 对象的构建,但我不太明白这个答案是否意味着我的问题肯定是“否”。如果没有,我想捕获布尔值中的常量以供进一步使用。
EDIT:正如 @DanielFrey 所指出的,构造函数不是测试常量性的好地方。那么 const 成员函数呢?
UPDATE:感谢大家纠正我最初提出的不适问题并提供答案的各个部分(构造函数定义不明确的常量、右值this
,上下文含义const
,事后看来,我忽略了明显的重载技巧,以及潜伏在阴影中的 const 引用别名漏洞)。对我来说,这个问题是 Stackoverflow 最好的回答。我决定选择 @JonathanWakely 的答案,因为它展示了如何定义Mutable
and Immutable
强化常量概念的课程,以万无一失的方式实现我想要的目标。
对于构造函数(原始问题)来说这是不可能的,因为
12.1 构造函数[class.ctor]
4 A constructor shall not be virtual
(10.3) or static
(9.4). A constructor can be invoked for a const
, volatile
or const volatile
object. A constructor shall not be declared const
, volatile
, or const volatile
(9.3.2). const
and volatile
semantics (7.1.6.1) are not applied on an object under construction. They come into effect when the constructor for the most derived object (1.8) ends. A constructor shall not be declared with a ref-qualifier.
对于成员函数(当前问题),您可以简单地提供const
和一个非const
重载,将两者转发到将常量作为布尔模板参数的(私有)方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)