C++模板和无符号长问题
我打算
const madness::Vector<double,3> kvec(0.0, 0.0, 1.0);
通过调用以下代码
template <typename T>
Vector<T,3> vec(T x, T y, T z) {
Vector<T,3> r; r[0] = x; r[1] = y; r[2] = z;
return r;
}
来创建一个常量 Vector不幸的是,我收到一个错误,似乎说
extra.cc:216: error: no matching function for call to ‘madness::Vector<double, 3ul>::Vector(double, double, double)’
note: candidates are: madness::Vector<T, N>::Vector(const madness::Vector<T, N>&) [with T = double, long unsigned int N = 3ul]
note: madness::Vector<T, N>::Vector() [with T = double, long unsigned int N = 3ul]
我忍不住注意到错误消息中的 3ul 。为什么编译器会认为我无辜的小三是unsigned long?
提前致谢, 缺口
I am intending to make a constant Vector
const madness::Vector<double,3> kvec(0.0, 0.0, 1.0);
By calling the following code
template <typename T>
Vector<T,3> vec(T x, T y, T z) {
Vector<T,3> r; r[0] = x; r[1] = y; r[2] = z;
return r;
}
Unfortunately, I get an error which seems to say
extra.cc:216: error: no matching function for call to ‘madness::Vector<double, 3ul>::Vector(double, double, double)’
note: candidates are: madness::Vector<T, N>::Vector(const madness::Vector<T, N>&) [with T = double, long unsigned int N = 3ul]
note: madness::Vector<T, N>::Vector() [with T = double, long unsigned int N = 3ul]
I can't help but notice the 3ul in the error message. Why does the compiler think my innocent little three is an unsigned long?
Thanks in advance,
Nick
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你的 Vector 类模板可能是:
你的 size_t 可能是一个 unsigned long 吗?
另外,我怀疑你的真正意思是:
is your Vector class template perhaps:
And is your size_t perhaps an unsigned long?
Also, I suspect you really meant:
如果您想使用 vec 函数,那么您需要
最终使用复制构造函数。按照您编写的方式,您需要为向量类提供一个需要三个双精度值的构造函数。
If you want to use your
vec
function then you need to dowhich will use the copy constructor ultimately. The way you've written it you would need to give the vector class a constructor that takes three doubles.
添加一个需要 3 个 double 的构造函数。您还没有,或者您错误地声明了它,或者您想使用
= { ... }
来使用聚合初始化而不是构造函数。选择适合的。至于
3u
- 您很可能将相应的模板参数声明为unsigned long int
。请注意,这有一个重要的结果:
您需要知道非类型模板参数的确切类型才能推断出参数。在这种情况下,您需要将
N
设为unsigned long int
。Add a constructor that takes 3 double. You haven't got one yet, or you declared it wrongly or instead of a constructor you want to use aggregate initialization using
= { ... }
. Choose what fits.As for the
3u
- you most probably declared the corresponding template parameter asunsigned long int
.Notice that this has an important consequence
You need to know the exact type of the non-type template parameter to be able to deduce arguments. In this case, you would need
N
to be aunsigned long int
.添加一个接受三个三输入的构造函数。就像这样:
Add a constructor that takes three three inputs. Like so: