检查对象是否是具有模板的类的实例

Check if object is instance of class with template

本文关键字:实例 对象 是否是 检查      更新时间:2023-10-16

我的类:

template < typename T >
Array<T>{};

(源数据存储在矢量中)

我有一个对象:

Array< string > a;
a.add("test");

我有一个目标:

Array< Array< string > > b;
b.add(a);

如何检查:

  1. b[0]Array的实例吗(与模板类型无关)
  2. a[0]是除Array之外的任何类型的实例吗

如果你可以使用C++11,创建你的类型特征;例如

#include <string>
#include <vector>
#include <iostream>
#include <type_traits>
template <typename T>
struct Array
{ 
std::vector<T> v;
void add (T const t)
{ v.push_back(t); }
};
template <typename>
struct isArray : public std::false_type
{ };
template <typename T>
struct isArray<Array<T>> : public std::true_type
{ };
template <typename T>
constexpr bool isArrayFunc (T const &)
{ return isArray<T>::value; }

int main()
{
Array<std::string> a;
Array<Array<std::string>> b;
a.add("test");
b.add(a);
std::cout << isArrayFunc(a.v[0]) << std::endl; // print 0
std::cout << isArrayFunc(b.v[0]) << std::endl; // print 1
}

如果您不能使用C++11或更新版本,而只能使用C++98,您可以简单地按照以下编写isArray

template <typename>
struct isArray
{ static const bool value = false; };
template <typename T>
struct isArray< Array<T> >
{ static const bool value = true; };

并避免包含type_traits

---编辑---

按照Kerrek SB的建议修改(在constexpr中转化)isArrayFunc()(谢谢!)。

下面是max66提出的解决方案的较短版本,不再使用结构isArray
它适用于C++98及更高版本。

#include <string>
#include <vector>
#include <iostream>
template <typename T>
struct Array
{ 
std::vector<T> v;
void add (T const t)
{ v.push_back(t); }
};
template <typename T>
constexpr bool isArrayFunc (T const &)
{ return false; }
template <typename T>
constexpr bool isArrayFunc (Array<T> const &)
{ return true; }
int main()
{
Array<std::string> a;
Array<Array<std::string>> b;
a.add("test");
b.add(a);
std::cout << isArrayFunc(a.v[0]) << std::endl; // print 0
std::cout << isArrayFunc(b.v[0]) << std::endl; // print 1
}

在c++中,您可以使用

if(typeid(obj1)==typeid(ob2))//or typeid(obj1)==classname
cout <<"obj1 is instance of yourclassname"

在您的情况下,您可以使用typeid(obj1)==std::array 进行检查