1

我有模板类

template <typename T>
class BST {
public:
      Node<T>* root;
...

我想根据 T 类型修改插入函数的行为。

我在寻找类似的东西

if(T instanceof Pair){

}
4

3 回答 3

2

您可以添加一个BST接受Pair类型的特化并相应地创建insert函数:

template <>
class BST<Pair>
{
   public:
       insert() { ... }
};
于 2013-04-29T23:55:05.113 回答
1

您可以使用std::is_same

if (std::is_same<T, Pair>::value)
于 2013-04-29T23:53:55.593 回答
1

您可以在 typeinfo 标头中使用“typeid”函数在 C++ 中实现此目的。

template<class T>
T fun(T a)
{
  if(typeid(T) == typeid(int))
  {
    //Do something
  }
  else if(typeid(T) == typeid(float))
  {
    //Do Something else
  }
}
于 2013-04-30T00:05:35.263 回答