我的类(class):
template < typename T >
Array<T>{};
(源数据存储在vector中)
我有一个对象:
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()
(谢谢!)。
关于c++ - 检查对象是否是带有模板的类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494844/