abr*_*ert 4 c++ templates variadic-templates stdarray
我有以下问题:
template< size_t... N_i >
class A
{
// ...
std::array< float, /* product of the unpacked elements of N_i */ > arr;
};
Run Code Online (Sandbox Code Playgroud)
如上所示,我尝试声明一个std::array名为arr一个类的成员A.在这里,我想要arr具有解包元素N_i的大小产品,例如,在A<2,3,4>"arr"的情况下应该具有大小2*3*4=24.
有谁知道这是如何实现的?
T.C*_*.C. 13
在C++ 17中:
std::array < float, (... * N_i)> arr;
Run Code Online (Sandbox Code Playgroud)
在C++ 14中:
// outside the class
template<size_t... Ns>
constexpr size_t product(){
size_t p = 1;
for(auto n : { Ns... }) p *= n;
return p;
}
// then
std::array< float, product<N_i...>()> arr;
Run Code Online (Sandbox Code Playgroud)
在C++ 11中:
template<size_t... N_i>
struct product {
static const size_t value = 1;
};
template<size_t N_1, size_t... N_i>
struct product<N_1, N_i...> {
static const size_t value = N_1 * product<N_i...>::value;
};
std::array< float, product<N_i...>::value> arr;
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用递归constexpr函数.
| 归档时间: |
|
| 查看次数: |
805 次 |
| 最近记录: |