C ++ - 类型特征问题

时间:2010-10-18 21:19:36

标签: c++ templates typetraits

我想知道在C ++中是否有可能以某种方式处理以下情况:

情况1) (易于处理)

class BasicFacility { }

template <typename U1, typename U2> class Facility : public BasicFacility { }

现在假设我们想要一些编译时断言,并且我们想检查任意类型typename T是否对Facility进行建模。这很简单:

(boost::is_base_of<BasicFacility, T>::type)

情况2) (???)

现在让我们假设在相同的情况下我们只有模板类:

template <typename U1, typename U2> class Facility { }

显然我们无法使用情境一中的相同解决方案,因为我们无法编写statement<Facility, T>Facility本身就是模板)。

那么,有没有一种方式(可能是脏的,涉及丑陋的演员,特定于对齐,可能有用的任何东西)来检查某些T是否实际上等于某些template type没有引入特定的空(辅助)基类(因为有时你根本不能)?

谢谢。

2 个答案:

答案 0 :(得分:8)

推出自己的测试非常简单:

template <typename T>
struct is_facility : public boost::false_type { };

template <typename U1, typename U2>
struct is_facility< Facility<U1, U2> > : public boost::true_type { };

答案 1 :(得分:4)

IIUC,您要确保某个模板参数是Facility模板的实例。这很简单:

template< typename Policy >
struct some_template; // note: only declared

template< typename U1, typename U1 >
struct some_template< Facility<U1,U2> > {
  // implementation
};

当然,您也可以概括/形式化:

template< typename T >
struct AssertFacility {}; // note: empty

template< typename U1, typename U2 >
struct AssertFacility< Facility<U1,U2> > {
  typedef Facility<U1,U2> result_t;
};

template< typename Policy >
class some_class {
  typedef AssertFacility<Policy>::result_t just_an_assertion;
public: 
  // more stuff
};
相关问题