【发布时间】:2015-05-06 13:42:04
【问题描述】:
我正在尝试使用c++ 重写java 代码。我一点也不精通c++。
原java代码
public static <T, K> K[] toArray(ITemplateCommand<T, K> command, List<T> templates) {
if (null == templates) {
return null;
}
K[] array = (K[]) Array.newInstance(command.getClassOfK(), templates.size());
for (int i = 0; i < templates.size(); i++) {
array[i] = command.buildTemplate(templates.get(i));
}
return array;
}
我的c++ 代码。
class TemplateImplementation {
public:
template<class K, class T>
static K* toArray(ITemplateCommand<T,K> *command, std::list<T>& templates) {
if (nullptr == templates) {
return nullptr;
}
std::array<command->getClassOfK(), templates.size()> arr; // no idea how to pass object type there
for(int i = 0; i < templates.size(); i++) {
arr[i] = command->buildTemplate(templates[i]);
}
}
};
在java 中,我创建了接口和多个实现,其中getClassOfK 返回了K 对象的类。
为了简化事情,我决定不创建实现,而只创建具有virtual 方法的类,用作接口。
template<class T, class K>
class ITemplateCommand {
public:
virtual K* buildTemplate(T* tmplate);
virtual std::type_info getClassOfK();
};
但是我在编译过程中出现了几个错误(我使用的是在线c++编译器)
sh-4.2# g++ -std=c++11 -o main *.cpp
main.cpp: In static member function 'static K* TemplateImplementation::toArray(ITemplateCommand<T, K>*, std::list<T>&)':
main.cpp:24:64: error: type/value mismatch at argument 1 in template parameter list for 'template<class _Tp, long unsigned int _Nm> struct std::array'
std::array<command->getClassOfK(), templates.size()> arr; // no idea how to pass object type there
^
main.cpp:24:64: error: expected a type, got 'command->.getClassOfK()'
main.cpp:24:69: error: invalid type in declaration before ';' token
std::array<command->getClassOfK(), templates.size()> arr; // no idea how to pass object type there
^
main.cpp:26:22: error: invalid types 'int[int]' for array subscript
arr[i] = command->buildTemplate(templates[i]);
但我的主要问题是 如何使用 std::type_info 将类类型传递给 std::array 的构造函数?还是无法使用此对象?
附:另外我知道从函数返回指针不是一个好主意,但我想让代码尽可能接近原始代码
【问题讨论】:
-
这里发生了根本性的不匹配。 C++ 模板基于编译时特化,因此您无法从运行时值创建模板。
-
嗯...原来的代码不能重写?
-
是的,你只需要懂c++。首先查看 std::vector,以及如何使用 c++ 模板参数。
-
哦!我明白了!我根本不需要
getClassOfK。因为使用了template声明,我可以简单地做std::array<K, templates.size()> arr;