在模板中发现对象的类型

时间:2012-12-20 13:21:43

标签: c++ templates

有没有比使用dynamic_cast更优雅的方式来发现模板参数的类型。实施例

template< typename TypeA, typename TypeB >
bool foo( TypeA* x, TypeB* y )

if( dynamic_cast< WantedType* >( x ) != NULL ) // More ellegant way of doing this
   // found specific type, setting its stuff

可能是一个专业化template< WantedType TypeA, ... >,但这会导致重复的代码执行相同的操作。

5 个答案:

答案 0 :(得分:3)

std::is_same<A,B>::value告诉您A和B是否属于同一类型。

然而,你犯的错误很可能。

dynamic_cast用于检查实例的运行时类型,这与许多上下文中相同变量的编译时类型不同。

答案 1 :(得分:2)

这是另一种选择,它可能更符合您的原始思路(不是说这是最好的方式):

尝试使用方法typeid(),(#include <typeinfo>)。

鉴于您的代码,您可以

if ( typeid( x ).name() == typeid( wantedType ).name() ) { ...

,其中wantType为intchar或其他。

修改

查看:http://msdn.microsoft.com/en-us/library/fyf39xec%28v=vs.80%29.aspx

似乎typeid的参数可以是任何对象。

答案 2 :(得分:1)

  

也许是专业化模板&lt; WantedType TypeA,...&gt;

无论是超载还是专业化都是必经之路。其他一切都是hacky,使代码更复杂。

  

但这会导致重复的代码执行相同的操作。

理想情况下不应该。如果你已经正确地分解了你的函数,那么只有最少的代码重复(=函数头)。

答案 3 :(得分:1)

您可以使用模板专门化进行编译时检查:

template <typename A>
class IsClassWantedType 
{
  public:
    static const bool value = false;
}

template <>
class IsClassWantedType <WantedType>
{
  public:
    static const bool value = true;
}

template< typename TypeA, typename TypeB >
bool foo( TypeA* x, TypeB* y )
{

  if( IsClassWantedType<TypeA>::value == true )
  {
    //Do Stuff
  }

}

请注意,这里没有多态...它不会检查派生类型 对于派生类型,您必须使用更复杂的 SFINAE 技巧。

答案 4 :(得分:0)

您可以使用typeid(t).name()来做到这一点。

示例代码:

#include <string>
#include <sstream>
#include <iostream>
#include <typeinfo>
using namespace std;



template <class T>
string toString(const T& t)
{
    std::stringstream ss;
    ss << t;

    cout<<"The Datatype is a "<< typeid(t).name()  <<" \n";

    return ss.str();
}



int main(void)
{

    string str;

    char c=123;
    str=toString(c );

    int i=1234;
    str=toString(i );

    double d=1234;
    str=toString(d );



  cout<<" \nPress any key to continue\n";
  cin.ignore();
  cin.get();

   return 0;
}

输出:

The Datatype is a char
The Datatype is a int
The Datatype is a double