我能否确定类型特征是否具有 const 修饰符
Can I determine, though typetraits, whether a type has the const modifier?
正如问题所说,我可以通过typetraits
找出一个类型是否具有const
修饰符吗?
在 C++11 中,您可以使用 std::is_const
.只需包含<type_traits>
标题。
在 C++03 中,自己实现这一点很容易:
template<typename T>
struct is_const
{
const static bool value = false;
};
template<typename T>
struct is_const<const T>
{
const static bool value = true;
};
如果你
有 c++11 支持,你可以使用 std::is_const。否则,请使用 boost::is_const。
struct Foo {};
#include <iostream>
#include <type_traits>
....
std::cout << std::is_const<Foo>::value << 'n'; // false
std::cout << std::is_const<const Foo>::value << 'n'; // true
相关文章:
- 是否应该在模板化代码中完全避免const
- 如果变量名称不跟在 char* 后面,const char* 是否有效?
- 是否有技术原因阻止 Java 中的 final C++ 像 const 一样严格?
- 知道模板参数在编译时是否为 const char*?
- "this"指向的对象是否与 const 对象相同?
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- std::vector::assign/std::vector::operator=(const&) 是否保证在"this"中重用缓冲区?
- const-ref传递的模板化参数是否经过优化,以便在足够小时按值传递
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- 如何检查函数是否真的获得了定义为 const 的变量?
- 修改数据是否由 const shared_ptr&Ok 传递?
- 从内部使用静态 std::string 的函数返回 const char * 是否安全?
- 是否可以交换在 c++ 中作为函数 func(say) 中的参数传递的 const 向量的两个元素,例如:vector<int>func (const vector<int>&
- 将shared_ptr转换为<T> shared_ptr<const T>是否会更改它所指向的对象?
- const 是否允许在这里进行(理论)优化?
- 删除标头中用作函数参数的"primitive"类型前面的"const"是否更好?
- 在处理无状态对象时,将它们标记为const是否仍有性能优势
- 对于obj(obj*const a=obj const*b),int*const a=int const*b是否为tru
- const是否意味着C++11中的线程安全