【发布时间】:2017-01-14 21:17:43
【问题描述】:
我在重载获取模板作为输入的函数时遇到问题。 我做了一个模板向量:
template TempVec<class T, int size>
它有两个选项:大小为 3 的 int 向量,或大小为 2 的复数向量。
我有一个名为InnerProduct 的函数,它获取两个向量并返回向量之间内积的结果。问题是返回值的类型取决于向量类型(int/complex)。
所以我创建了这三个函数(在 TempVec 类中):
template <class T, int size>
friend int InnerProduct(const TempVec<T, 3>& v1, const TempVec<T, 3>& v2);
template <class T, int size>
friend complex InnerProduct(const TempVec<T, 2>& v1, const TempVec<T, 2>& v2);
template <class T, int size>
friend TempVec<T, size> InnerProduct(const TempVec<T, size>& v1, const TempVec<T, size>& v2);
当我调用InnerProduct 时,我总是会到达最后一个函数(最通用的函数),即使我传递了两个大小为 3 的向量或两个大小为 2 的向量。我试图摆脱最后一个函数,但我得到了错误:
'InnerProduct': none of the 2 overloads could convert all the argument types.
我将非常感谢您对该问题的一些解释/解决方案。
【问题讨论】:
标签: c++ templates overloading