C++ 为什么我的isVector函数不返回true?
基于这个问题,我尝试了一个C++ 为什么我的isVector函数不返回true?,c++,constexpr,decltype,C++,Constexpr,Decltype,基于这个问题,我尝试了一个is\u向量trait: #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::vec
is\u向量
trait:
#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;
}
这正如预期的那样有效。但是,当我尝试将其放入一个小的辅助函数中时,is_vector
返回false
forB
:
template<typename T>
constexpr bool isVector(const T& t) {
return is_vector<decltype(t)>::value;
}
...
cout << "B: " << isVector(B) << endl; // Expected ouptput: "B: 1"
我在这里遗漏了什么?这里的问题是
t
是一个const std::vector&
,它与struct is_vector
不匹配。在函数中真正需要的是使用T
,它被推断为std::vector
,它确实有效。这样做你会得到什么
template<typename T>
constexpr bool isVector(const T& t) {
return is_vector<T>::value;
}
模板
constexpr bool isVector(const T&T){
返回值为_vector::value;
}
好吧,t
是const std::vector&
。也要感谢你@BoPersson的快速响应。几乎被愚弄了:谢谢你的解释,现在我觉得自己很傻。我会尽快接受你的回答。@PhilippLudwig没问题。很乐意帮忙。
B: 0
template<typename T>
constexpr bool isVector(const T& t) {
return is_vector<T>::value;
}