我能否确定类型特征是否具有 const 修饰符

Can I determine, though typetraits, whether a type has the const modifier?

本文关键字:const 是否 特征 类型      更新时间:2023-10-16

正如问题所说,我可以通过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
相关文章: