我在推导 c++ 数组的单个元素的类型时遇到问题。
我想实现以下目标:
template <class T>
struct array_element { };
template <class T>
struct array_element<T[]> {
using type = T;
};
int main() {
int a[5] = {1, 2, 3, 4, 5};
array_element<decltype(a)>::type element = a[0];
}
但是代码显然不能编译(int[5]不匹配T[])...
最佳答案
你需要一个额外的参数来进行特化:
template <class T, size_t N>
struct array_element<T[N]> {
using type = T;
};
或者:
std::remove_reference<decltype(a[0])>::type element = a[0];
或者:
auto element = a[0];
关于c++ - 有没有办法在c++中推断出数组的单个元素的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37411841/