爲什麼std::remove_const
不能將const T&
轉換爲T&
?這個不可否認的虛構的例子演示了我的問題:std :: remove_const與常量引用
#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的引用。 – xaxxon 2016-07-14 09:19:17