我正在将一些Java代码翻译成C ++,但是我遇到了这个函数的问题。
private static boolean isArray(Object aObject){
return aObject.getClass().isArray();
}
基本上,我需要知道对象是否是任何类型和任何模板的向量。 (我在C ++代码中使用向量而不是数组。)
例如,输出应该是这样的。//define some variables
int a=3;
double arr[]={1.0,2.0,3.0,4.0};
vector<int> vecint ({1,2,3});
vector<double> vecdouble ({1.0,2.0});
Class B {};
//function output:
bool b;
b=function(a); //returns false
b=function(arr); // returns false
b=function(vecint); //returns true
b=function(vecdouble); //returns true
b=function(B); //returns false
答案 0 :(得分:2)
这是利用Java的设计(主要是所有内容都来自Object
)。 C ++没有这样的要求。当您声明std::vector
时,它是一个向量。如果不是,那就不是。除非你有一个带有void*
的可怕函数声明,否则你需要指定函数所采用的参数类型(显式或通过模板)。
答案 1 :(得分:2)
在C ++中,并非所有东西都是对象。一个函数可以使用任何,而不是C ++中的所有东西都是一个对象。因此,如果传递给函数的一些随机事物是vector
或完全不相关的东西,那么很难进行运行时推论。而且,如果不诉诸void*
(请不要),template
或某种{{} {1}}对象。
但是我们可以利用一些模板元编程在编译时推导出它:
variant
输出:
#include <cstdlib>
#include <vector>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
template <typename Type>
class IsArray;
template<typename Element> class IsArray <vector <Element>>
{
public:
enum { mValue = true };
};
template<typename Item> class IsArray
{
public:
enum { mValue = false };
};
int main()
{
int n = 42;
cout << "An int is a vector: " << boolalpha << IsArray<int>::mValue << endl;
vector <int> v;
cout << "A vector <int> is a vector: " << boolalpha << IsArray<vector<int>>::mValue << endl;
}
实际上,这可以进一步简化为出现,就像我们在运行时进行演绎,即使它仍在编译时进行:
An int is a vector: 0
A vector <int> is a vector: 1
输出相同。
答案 2 :(得分:1)
您需要使用类型特征。我的意思是,编译器在编译代码时知道类型,并将它应用于适当重载的函数(或本例中的构造函数),并且您可以使用它来获得优势。让我们为矢量做一个类型特征。
//A type trait for a vector
template <typename T> struct Is_Vector { static const bool value = false; };
template <> struct Is_Vector<std::vector<T>> { static const bool value = true; };
您为类型Is_Vector
指定一个矢量类型,并将其数据成员value
设置为true;否则,其数据成员value
将设置为false。
现在让我们创建一个使用此类型特征的函数
// A function that identifies whether the argument is a vector or not
template <typename Type>
bool isVector(Type object){
return Is_Vector<Type>::value;
}
测试出来:
int main(){
std::vector<int> vector;
int integer;
std::cout << std::boolalpha;
std::cout << isVector(vector) << '\n';
std::cout << isVector(integer) << '\n';
}
对第一个函数生成true,对第二个函数生成false。最好的是,类型在编译时计算出来。
或者,您可以使用两个模板化函数来完成此操作,其中一个是专门的。
//the compiler will choose this one if you pass in a vector
template <typename T>
bool isVector(std::vector<T> vector_object){
return true;
}
//the compiler will choose this one if you pass in something other than a vector
template <typename T>
bool isVector(T everything_else){
return false;
}