考虑下面的模板dump
函数:
namespace {
using namespace Eigen;
using namespace std;
using namespace vMAT;
template <typename T>
NSString *
dump(NSString * prefix, T * A, vMAT_Size sizeA)
{
NSMutableString * dump = [NSMutableString stringWithString:prefix];
[dump appendString:@" = \n"];
Eigen::Map<Matrix<T, Dynamic, Dynamic>> DATA(A, sizeA[0], sizeA[1]);
stringstream out;
out << DATA << endl;
[dump appendFormat:@"%s", out.str().c_str()];
return dump;
}
template <> // Specialized so elements print as numbers instead of chars
NSString *
dump(NSString * prefix, int8_t * A, vMAT_Size sizeA)
{
NSMutableString * dump = [NSMutableString stringWithString:prefix];
[dump appendString:@" = \n"];
Eigen::Map<Matrix<int8_t, Dynamic, Dynamic>> DATA(A, sizeA[0], sizeA[1]);
stringstream out;
out << DATA.cast<int32_t>() << endl;
[dump appendFormat:@"%s", out.str().c_str()];
return dump;
}
template <> // Specialized so elements print as numbers instead of chars
NSString *
dump(NSString * prefix, uint8_t * A, vMAT_Size sizeA)
{
NSMutableString * dump = [NSMutableString stringWithString:prefix];
[dump appendString:@" = \n"];
Eigen::Map<Matrix<uint8_t, Dynamic, Dynamic>> DATA(A, sizeA[0], sizeA[1]);
stringstream out;
out << DATA.cast<uint32_t>() << endl;
[dump appendFormat:@"%s", out.str().c_str()];
return dump;
}
}
如您所见,我已经复制/粘贴/编辑了它以专门处理如何转储int8_t
和uint8_t
矩阵。但这正是模板应该消除的那种疯狂!
我试图向typename AsT
原始函数添加一个额外的模板参数,但一直运行与抱怨这一行的编译器发生冲突:
out << DATA.cast<AsT>() << endl;
Xcode 抱怨它cast<AsT>()
是一个“依赖模板”并想template
在它前面插入关键字……这似乎是一种无意义的语法,然后会产生另一个编译器错误。
将这个模板函数专门用于 int8_t 和 uint8_t 的更好方法是什么?