我对模板有点陌生,我正在尝试修改一些为 c++ 提供矩阵和向量操作的库,我有一个向量类,我试图重载 operator() 以便它处理像这样的操作 Vector (2:5) 将返回一个向量,其中包含原始向量的 2,3,4,5 元素,我正在使用一个名为冒号的类,其中冒号 (2:5) 将 (2:5) 效果表示为我发现 c++ 没有运算符:。希望我给了一个适当的介绍。相关代码如下
向量类
template< size_t M, typename T = float >
class Vector
{
public:
typedef T value_type;
inline T& operator()( size_t index );
inline const T& operator()( size_t index ) const;
template <size_t N> Vector<N,T> operator()(const colon &cex) const;
.
.
}
以及相应的实现
template< size_t M, typename T >
template< size_t N>
Vector<N,T>
Vector<M,T>::operator()( const colon &cex ) const
{
long i, ii, st = 0, in = 0, en = 0, s;
cex.apply(M, st, in, en, s);
if (s && (st>0) && (st>M))
{
Vector<N,T> result;
for (i=st,ii=0;i+=in,ii++;i<=en,ii<N)
{
result(ii)=array(i);
return result;
}
}
return 0;
}
这里的 return 0 只是一个占位符,它应该返回一个空向量。冒号类(取自另一个库并由我修改)。
class colon
{
public:
/// Colon expression '(:)'
colon() { _flag = 'a'; }
/// Colon expression of type '(2:5)'
colon(long s, long e) { _s = s; _i = 1; _e = e; _flag = 'r'; }
void apply(long s, long &f, long &i, long &l, long &n) const;
private:
/// Type of colon expression.
char _flag;
/// First index.
long _s;
/// Increment.
long _i;
/// Last index.
long _e;
}; /* class colon */
相关的实现是
void
colon::apply(long n, long &st, long &in, long &en,
long &le) const
{
switch (_flag)
{
case 'r':
if ((_i == 0 ) || ((_e - _s) / _i < 0 )) le = 0;
else
{
st = _s;
in = _i;
en = _e - (_e - _s) % _i;
le = (_e - _s) / _i + 1;
}
break;
case 'a':
if (n)
{
st = 1;
in = 1;
en = n;
le = n;
}
else le = 0;
break;
}
}
用于测试功能的代码是
bool ok = true;
Vector< 4, double > v;
double data[] = { 1, 2, 3, 4 };
v.iter_set( data, data+4 );//just puts elements of data inside v with the same type
// test Vector colon
{
bool ok = true;
Vector<3,long> test;
test=v(colon(2,4));//Problem
}
现在的错误是
C2664: 'const double &Vector<M,T>::operator ()(size_t) const' :
cannot convert parameter 1 from 'colon' to 'size_t'
编译器的输出是
error C2664: 'const double &Vector<M,T>::operator ()(size_t) const' :
cannot convert parameter 1 from 'colon' to 'size_t'
with
[
M=4,
T=double
]
No user-defined-conversion operator available that can perform this conversion,
or the operator cannot be called
???帮助表示赞赏