经过多年的缺席,我将回到 C++(或者从技术上讲,Objective-C++),所以请多多包涵。我正在尝试使用模板来实现一个解决方案,否则它需要大量的剪切和粘贴代码。下面的摘录显示了这项工作的基本要点:
namespace {
using vMAT::DOUBLE;
using vMAT::SINGLE;
using vMAT::INT8;
using vMAT::UINT8;
using vMAT::INT16;
using vMAT::UINT16;
using vMAT::INT32;
using vMAT::UINT32;
using vMAT::INT64;
using vMAT::UINT64;
typedef void (* swapFn)(void * vector, vDSP_Length vectorLength);
// Functor used for template arguments.
template <typename TypeA>
struct swapbytes {
swapFn fn;
swapbytes()
{
if (sizeof(TypeA) == 8) fn = vMAT_byteswap64;
else if (sizeof(TypeA) == 4) fn = vMAT_byteswap32;
else if (sizeof(TypeA) == 2) fn = vMAT_byteswap16;
else if (sizeof(TypeA) == 1) fn = NULL;
else NSCAssert(NO, @"Oops!");
}
void operator()(void * vector, vDSP_Length vectorLength) const
// ..................................................... ^^^^^ Why?
{
if (fn != NULL) fn(vector, vectorLength);
}
};
template <typename TypeA, typename ClassB>
void
loadFromOperation(vMAT_MATv5NumericArray * self,
vMAT_MATv5ReadOperation * operation,
TypeA a,
ClassB b)
{
swapbytes<TypeA> SwapA;
long lenC = self.size[0] * sizeof(TypeA);
TypeA * C = (TypeA *)malloc(lenC);
long lenD = vMAT_Size_prod(self.size) * sizeof(ClassB);
self.arrayData = [NSMutableData dataWithCapacity:lenD];
self.arrayData.length = lenD;
ClassB * D = (ClassB *)[self.arrayData mutableBytes];
__block long idxD = 0;
vMAT_Size123Iterator(self.size, ^(int32_t n, int32_t o, int32_t p) {
[operation readComplete:C
length:lenC];
if (operation.swapBytes) { SwapA((void *)C, lenC / sizeof(TypeA)); }
for (int m = 0;
m < self.size[0];
m++) {
D[idxD] = C[m];
++idxD;
}
});
free(C);
}
}
- (void)_load_miUINT8_mxDOUBLE_fromOperation:(vMAT_MATv5ReadOperation *)operation;
{
loadFromOperation(self, operation, UINT8, DOUBLE);
}
我希望从以“为什么?”结尾的评论中可以看出我的问题是,为什么const
这里需要声明?如果省略,编译器会抱怨SwapA(...)
在loadFromOperation
.
SwapA
如果明确声明为,我会理解这一点const
,但事实并非如此。显然它可能是,因为它的操作不依赖于改变任何状态,但这不是重点。
虽然我对这段代码有另一双有用的眼睛,但我欢迎更精通 C++ 实践者可能愿意提供的任何风格或其他评论……</p>