检查对象是否是具有模板的类的实例
Check if object is instance of class with template
我的类:
template < typename T >
Array<T>{};
(源数据存储在矢量中)
我有一个对象:
Array< string > a;
a.add("test");
我有一个目标:
Array< Array< string > > b;
b.add(a);
如何检查:
b[0]
是Array
的实例吗(与模板类型无关)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 进行检查
相关文章:
- 对象实例化调用构造函数的次数太多
- C++ 中的基本单一实例对象
- 在 C++ 中,类实例对象 do memcpy 总是崩溃
- C++:在函数中使用当前实例(对象)
- 单一实例对象是否通过线程安全返回shared_ptr
- std::system 实例化单一实例对象时的异常
- 使用unique_ptr的单一实例对象
- 如果已创建 mongocxx::实例对象,则无法创建该对象
- 单一实例对象的未解决外部符号链接错误
- 实例对象如何查看函数的对象参数的私有成员?
- 在C++中调用单一实例对象的正确方法
- 声明模板化实例对象的函数指针
- 如何在"boost::function"中访问类实例(对象)指针?
- 删除单一实例对象 cpp 时出现内存泄漏
- 从 EXE 和 DLL 访问单一实例对象中的成员变量
- 如何在 C++11 中将 vector 与引用类型实例对象一起使用
- 为什么在构造函数退出时创建新的实例(对象)
- "类实例对象"未在此范围内声明
- c++实例对象的函数指针
- 如何正确存储多个实例对象