【发布时间】:2020-06-22 19:03:09
【问题描述】:
我正在尝试创建一个返回零填充数组的函数... 按照Elegantly define multi-dimensional array in modern C++我定义:
template<typename U, std::size_t N, std::size_t... M>
struct myTensor{
using type = std::array<typename myTensor<U, M...>::type, N>;
};
template<typename U, std::size_t N>
struct myTensor<U,N>{
using type = std::array<U, N>;
};
template<typename U, std::size_t... N>
using myTensor_t = typename myTensor<U, N...>::type;
然后我定义以下模板函数来填充零:
template<typename U, std::size_t N, std::size_t... M>
myTensor_t<U, N, M...> Zero_Tensor(){
myTensor_t<U, N, M...> res;
for(int i=0; i<N; i++)
res[i] = Zero_Tensor<U, M...>();
return res;
};
template<typename U, std::size_t N>
myTensor_t<U, N> Zero_Tensor(){
myTensor_t<U, N> res;
for(int i=0; i<N; i++)
res[i] = U(0);
return res;
};
例如当我这样做时
class myclass{
myTensor_t<int,3,3,5> x;
};
它编译得很好。如果我尝试这样做:
class myclass{
myTensor_t<int,3,3,5> x=Zero_Tensor<int,3,3,5>();
};
编译时出现以下错误:
src/mytensor.hpp(107): error: no instance of overloaded function "Zero_Tensor" matches the argument list
res[i] = Zero_Tensor<U, M...>();
^
src/mytensor.hpp(112): note: this candidate was rejected because function is not visible
myTensor_t<U, N> Zero_Tensor(){
^
src/mytensor.hpp(104): note: this candidate was rejected because at least one template argument could not be deduced
myTensor_t<U, N, M...> Zero_Tensor(){
^
detected during:
instantiation of "myTensor_t<U, N, M...> Zero_Tensor<U,N,M...>() [with U=int, N=5UL, M=<>]" at line 107
instantiation of "myTensor_t<U, N, M...> Zero_Tensor<U,N,M...>() [with U=int, N=3UL, M=<5UL>]" at line 107
instantiation of "myTensor_t<U, N, M...> Zero_Tensor<U,N,M...>() [with U=int, N=3UL, M=<3UL, 5UL>]" at line 36 of "src/myclass.hpp"
我真的不明白this candidate was rejected because function is not visible 告诉我什么。我想我不明白为什么它不可见?任何帮助表示赞赏。
【问题讨论】:
-
res[i] = Zero_Tensor(); zero_tensor 中的这一行不会创建无限循环。
-
请注意,
Zero_Tensor函数的定义可以简化为一行:return myTensor_t<U, N, M...>{};。值初始化std::array值初始化数组的每个元素,对于像int这样的数字类型,会将它们归零。 -
@SudipGhimire 我认为递归已被
myTensor_t<U, N> Zero_Tensor()停止。至少这是我的理解,也许我的想法完全不正确。 -
@MilesBudnek 我明白你的意思,非常正确。但是,当我没有原始类型时会发生什么?我将把它用于最终具有明确定义的
U(0)的某些类类型。再往下走,而不是只进行零初始化,我将使用一些定义良好的U(something)进行持续初始化。我从来没有在问题中解释过,所以我很抱歉。
标签: c++ variadic-templates explicit-instantiation