【发布时间】:2013-04-08 19:19:21
【问题描述】:
为什么std::remove_const 不能将const T& 转换为T&?这个公认的相当人为的例子证明了我的问题:
#include <type_traits>
int main()
{
int a = 42;
std::remove_const<const int&>::type b(a);
// This assertion fails
static_assert(
!std::is_same<decltype(b), const int&>::value,
"Why did remove_const not remove const?"
);
return 0;
}
上面的情况很容易解决,所以对于上下文,想象一下:
#include <iostream>
template <typename T>
struct Selector
{
constexpr static const char* value = "default";
};
template <typename T>
struct Selector<T&>
{
constexpr static const char* value = "reference";
};
template <typename T>
struct Selector<const T&>
{
constexpr static const char* value = "constref";
};
int main()
{
std::cout
<< Selector<typename std::remove_const<const int&>::type>::value
<< std::endl;
return 0;
}
在上面的示例中,我希望显示reference,而不是constref。
【问题讨论】:
-
记住,没有 const 引用,只有 const 引用。