c++ - 检查对象是否是带有模板的类的实例

标签 c++ class templates typechecking

我的类(class):

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

(源数据存储在vector中)

我有一个对象:

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()(谢谢!)。

关于c++ - 检查对象是否是带有模板的类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494844/

相关文章:

C++ SFINAE enable_if_t 在成员函数中,如何消除歧义?

c++ - 在 C++ 中使用具有相同方法的类中调用非成员函数

c++ - 在qt中创建一个qstate

c++ - 虚拟最佳实践

使用或不使用的 PHP Getters/Setter

C++:如何在类和基元上使用模板?

c++ - Qt : Write in file

php:我可以在类方法中创建和调用函数吗?

class - 在 ANT 中制作 JAR 时如何有条件地包含 list 选项

python - 如何编写具有多个循环元素的字符串模板文件?