【发布时间】:2018-05-07 06:31:48
【问题描述】:
我一直在尝试创建一个类,该类表示数组的非拥有、多维视图(有点像 N 维 std::string_view),其中维数是“动态”变化的。即维度数量和维度大小与类无关,而是在访问元素时指定(通过operator())。以下代码总结了我正在寻找的功能:
#include <array>
#include <cstddef>
template<typename T>
struct array_view {
T* _data;
// Use of std::array here is not specific, I intend to use my own, but similar in functionality, indices class.
template<std::size_t N>
T& operator()(std::array<std::size_t, N> dimensions, std::array<std::size_t, N> indices) const
{
std::size_t offset = /* compute the simple offset */;
return _data[offset];
}
};
int main()
{
int arr[3 * 4 * 5] = {0};
array_view<int> view{arr};
/* Access element 0. */
// Should call array_view<int>::operator()<3>(std::array<std::size_t, 3>, std::array<std::size_t, 3>)
view({5, 4, 3}, {0, 0, 0}) = 1;
}
但是这个fails to compile(忽略operator()中明显的语法错误)与
main.cpp: In function 'int main()':
main.cpp:28:27: error: no match for call to '(array_view<int>) (<brace-enclosed initializer list>, <brace-enclosed initializer list>)'
view({5, 4, 3}, {0, 0, 0}) = 1;
^
main.cpp:11:5: note: candidate: 'template<long unsigned int N> T& array_view<T>::operator()(std::array<long unsigned int, N>, std::array<long unsigned int, N>) const [with long unsigned int N = N; T = int]'
T& operator()(std::array<std::size_t, N> dimensions, std::array<std::size_t, N> indices) const
^~~~~~~~
main.cpp:11:5: note: template argument deduction/substitution failed:
main.cpp:28:27: note: couldn't deduce template parameter 'N'
view({5, 4, 3}, {0, 0, 0}) = 1;
^
我不是模板实例化/演绎方面的专家。然而,在我看来,编译器试图从std::initializer_list<int> 参数中推断出N,但由于operator() 被声明为采用std::array<std::size_t, N> 参数而失败。因此编译失败。
执行another, far more simplified, experiment,显示类似结果:
template<typename T>
struct foo {
T val;
};
struct bar {
template<typename T>
void operator()(foo<T>) {}
};
int main()
{
bar b;
b({1});
}
输出:
main.cpp: In function 'int main()':
main.cpp:14:7: error: no match for call to '(bar) (<brace-enclosed initializer list>)'
b({1});
^
main.cpp:8:10: note: candidate: 'template<class T> void bar::operator()(foo<T>)'
void operator()(foo<T>) {}
^~~~~~~~
main.cpp:8:10: note: template argument deduction/substitution failed:
main.cpp:14:7: note: couldn't deduce template parameter 'T'
b({1});
似乎编译器甚至没有尝试将{1}(这是foo<int> 的有效初始化)转换为foo<int>,因为它在未能推断出函数模板参数后停止。
那么有什么方法可以实现我正在寻找的功能吗? 是否有一些我遗漏的新语法,或者可以替代的方法,或者根本不可能?
【问题讨论】:
标签: c++ templates c++17 template-argument-deduction