#define T int
int main ()
{
const T x = 2;
// (1) -- type of `x` is compared with `T`
static_assert(std::is_same<std::remove_const<decltype(x)>::type, T>::value, "Not same");
// (2) -- type of `x` is compared with `const T`
static_assert(std::is_same<std::remove_const<decltype(x)>::type, const T>::value, "Not same");
}
以上代码按预期工作。其中 (1) 通过,(2) 失败。
然而,它以相反的方式发生,即。 (1) 失败,(2) 通过,如果我进行以下更改:
#define T int& // <--- added reference
为什么会这样?
使用decltype
的类似代码,我们可以在代码中添加什么,以便 (1) 传递引用和非引用类型,即 int&
& int
?
也欢迎使用 const_cast
的可能解决方案。
注意:因为我想宏观地从对象中删除 const
;我用过decltype
。
因为您使用了文本替换宏而不是 typedef,所以您得到了 const int& x
。
const int&
不是 const
类型,因此 remove_const
什么都不做。
不可能更改引用的 const
特性,因为 C++ 没有任何引用变异操作。
如果你想删除最里面的 const
(const T
会放置它),那么这个可行:
template <typename T>
struct remove_deepest_const_impl { typedef T type; };
template <typename T>
struct remove_deepest_const_impl<const T> { typedef T type; };
template <typename T>
struct remove_deepest_const_impl<T*>
{ typedef typename remove_deepest_const_impl<T>::type* type; };
template <typename T>
struct remove_deepest_const_impl<T* const>
{ typedef typename remove_deepest_const_impl<T>::type* const type; };
template <typename T>
struct remove_deepest_const_impl<T&>
{ typedef typename remove_deepest_const_impl<T>::type& type; };
template <typename T>
struct remove_deepest_const_impl<T&&>
{ typedef typename remove_deepest_const_impl<T>::type&& type; };
template <typename T> using remove_deepest_const
= typename remove_deepest_const_impl<T>::type;
演示:https://rextester.com/OUTIN28468