C++ 模板非类型参数算法

标签 c++ templates parameters template-specialization

我正在尝试通过以下方式专门化模板:

template<size_t _1,size_t _2> // workaround: bool consecutive = (_1 == _2 - 1)>
struct integral_index_ {};
...
template<size_t _1>
struct integral_index_<_1, _1 + 1> { // cannot do arithmetic?
//struct integral_index_<_1, _2, true> { workaround
};

但是我收到编译器消息错误

the template argument list of the partial specialization includes a non
-type argument whose type depends on a template parameter.

我做错了什么? 谢谢

我在评论中提出了解决方法。显然我不能在模板特化中做算术?似乎违反直觉。

这里是我要解决的问题的最终解决方案。基本上,连续索引只需要一次乘法。

130 template<size_t _1,size_t _2, bool consecutive = (_1 == _2 - 1)>
131 struct integral_index_ {
132     template<typename T, typename U>
133     __device__
134     static T eval(const T (&N)[4], const U &index) {
135         T j = index/N[_1];
136         return ((index - j*N[_1])*range<0,_1>::multiply(N) +
137                 j*range<0,_2>::multiply(N));
138     }
139 };
140
141 template<size_t _1,size_t _2>
142 struct integral_index_<_1, _2, true> {
143     template<typename T, typename U>
144     __device__
145     static T eval(const T (&N)[4], const U &index) {
146         return index*range<0,_1>::multiply(N);
147     }
148 };
149
150 template<size_t _1,size_t _2, typename T, typename U>
151 __device__
152 T integral_index(const T (&N)[4], const U &index) {
153     return integral_index_<_1,_2>::eval(N, index);
154 }

最佳答案

我发布的解决方案是 GMan 建议的

130 template<size_t _1,size_t _2, bool consecutive = (_1 == _2 - 1)>
131 struct integral_index_ {
132     template<typename T, typename U>
133     __device__
134     static T eval(const T (&N)[4], const U &index) {
135         T j = index/N[_1];
136         return ((index - j*N[_1])*range<0,_1>::multiply(N) +
137                 j*range<0,_2>::multiply(N));
138     }
139 };
140
141 template<size_t _1,size_t _2>
142 struct integral_index_<_1, _2, true> {
143     template<typename T, typename U>
144     __device__
145     static T eval(const T (&N)[4], const U &index) {
146         return index*range<0,_1>::multiply(N);
147     }
148 };
149
150 template<size_t _1,size_t _2, typename T, typename U>
151 __device__
152 T integral_index(const T (&N)[4], const U &index) {
153     return integral_index_<_1,_2>::eval(N, index);
154 }

关于C++ 模板非类型参数算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2615905/

相关文章:

c++ - 无法在 Visual Studio 2015 中将 typedef 转换为 std::pair

c++ - DLL-导出模板基类的静态成员

c++ - ListView 控件忽略扩展样式

c++ - 调用 operator() 时是否可以提供模板参数?

c++ - 根据 C++ 中的用户输入更改模板类型

python - 如何从 pytest_addoptions 访问 pytest conftest 中的命令行输入并在 fixture 参数中使用它?

android - 无法从深层链接获取 Uri 数据

c - 函数中的参数太少

c++ - 可以将共享指针与非指针数据成员混合使用吗?

c++ - SDL 窗口立即关闭