从模板切换传递的类型 [英] Switch passed type from template

查看:148
本文介绍了从模板切换传递的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中可以检查传入模板函数的类型吗?例如:

Is it possible in C++ to check the type passed into a template function? For example:

template <typename T>
void Foo()
{
   if (typeof(SomeClass) == T)
      ...;
   else if (typeof(SomeClass2) == T)
      ...;
}


推荐答案

template < typename T >
void foo()
{
  if (is_same<T,SomeClass>::value) ...;
  else if (is_same<T,SomeClass2>::value) ...;
}

您可以获得 is_same 根据你的愿望/编译器从 std :: boost :: 前者只在C ++ 0x中。

You can get is_same from std:: or boost:: depending on your desire/compiler. The former is only in C++0x.

问题出在 ... 中。如果你期望能够做一些特定于foo中的那些类型的函数调用,你很可惜地错了。即使该代码段从不运行,当你传递的东西不服从预期的接口时,也会导致编译器错误。

The problem comes with what is in .... If you expect to be able to make some function call specific to those types within foo, you are sadly mistaken. A compiler error will result even though that section of code is never run when you pass in something that doesn't obey that expected interface.

要解决这个问题,你需要做一些有点不同。我建议使用标记分派功能:

To solve THAT problem you need to do something a bit different. I'd recommend tag dispatching:

struct v1_tag {};
struct v2_tag {};

template < typename T > struct someclass_version_tag;
template < > struct someclass_version_tag<SomeClass> { typedef v1_tag type; };
template < > struct someclass_version_tag<SomeClass2> { typedef v2_tag type; };

void foo(v1_tag) { ... }
void foo(v2_tag) { ... }
template < typename T > void foo()
{
  typedef typename someclass_version_tag<T>::type tag;
  foo(tag());
}

注意,这里不会遇到任何运行时多态性开销,打开它应该导致相同或更小的代码大小和速度(虽然你不应该担心,反正,直到你运行一个profiler)。

Note that you will not be suffering any runtime-polymorphism overhead here and with optimizations turned on it should result in the same or even smaller code size AND speed (though you shouldn't be worrying about that anyway until you've run a profiler).

这篇关于从模板切换传递的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆