Phi*_*wig 3 c++ decltype constexpr
基于这个问题,我尝试了一个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& t) {
return is_vector<decltype(t)>::value;
}
...
cout << "B: " << isVector(B) << endl; // Expected ouptput: "B: 1"
Run Code Online (Sandbox Code Playgroud)
输出:
B: 0
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?
这里的问题t是一个const std::vector<int>&不匹配的问题struct is_vector<std::vector<T>>.你真正想要的功能是使用T推导出的功能std::vector<T>.你做到了
template<typename T>
constexpr bool isVector(const T& t) {
return is_vector<T>::value;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |