这是如何检查对象是否为常量的问题?.
我很惊讶地看到以下程序
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_const<const int&>::value << "\n";
}
Run Code Online (Sandbox Code Playgroud)
产生了这个输出
false
在什么情况下将其const int&视为非const类型是有意义的?
基于这个问题,我尝试了一个is_vector特点:
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
struct is_vector {
constexpr static bool value = false;
};
template<typename T>
struct is_vector<std::vector<T>> {
constexpr static bool value = true;
};
int main() {
int A;
vector<int> B;
cout << "A: " << is_vector<decltype(A)>::value << endl;
cout << "B: " << is_vector<decltype(B)>::value << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
A: 0
B: 1
Run Code Online (Sandbox Code Playgroud)
这按预期工作.然而,当我试图把这个小的辅助函数,is_vector返回false为B:
template<typename T>
constexpr bool isVector(const T& …Run Code Online (Sandbox Code Playgroud)