Cha*_* Ye 4 c++ template-meta-programming
我记得十年前,有一段代码使用c ++模板元编程,可以从数组名称中推断出数组维度.
例如
int a[2][3][4][5][6];
cout << DimOfArray(a) << endl
Run Code Online (Sandbox Code Playgroud)
输出:
5
Run Code Online (Sandbox Code Playgroud)
但我忘记了该代码的细节.我记得它使用了sizeof(a)/sizeof(a[0])技巧.有谁知道如何写它?
原始代码可能构建了今天由std :: rank提供的内容,请参阅"可能的实现"部分; 因为不必从整数常量继承(那些日子里不存在),它可以修改为:
template<typename T>
struct rank { static size_t const value = 0U; };
template<typename T>
struct rank<T[]> { static size_t const value = rank<T>::value + 1; };
template<class T, std::size_t N>
struct rank<T[N]> { static size_t const value = rank<T>::value + 1; };
Run Code Online (Sandbox Code Playgroud)
然后代码将在模板函数中使用此模板类(模板类也可能是函数中的本地类):
template <typename T>
size_t dimOfArray(T const& array)
{
return /*std::*/rank<T>::value;
}
Run Code Online (Sandbox Code Playgroud)
用现代C++最好的声明这个功能constexpr.如果你在获得一个特定维度的大小后,可以使用:
template <typename T, size_t N>
size_t dimOfArray(T const (&array)[N]) constexpr
{
return N;
}
Run Code Online (Sandbox Code Playgroud)
再次,今天你可能想拥有它constexpr(如图所示).
后者(特定维度的大小)也是你可以通过sizeof(a)/sizeof(*a)"技巧" 实现的(而不是更简单的返回N),但我没有看到你如何想要获得维度的数量.
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |