这个问题已经在这里有一个答案:
#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
可能的解决方法也欢迎。
注意:因为我想宏观FY从对象去除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;