【问题标题】:C++ - type traits questionC++ - 类型特征问题
【发布时间】:2010-10-18 21:19:36
【问题描述】:

我想知道在 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&lt;Facility, T&gt;Facility 本身就是一个模板)。

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

谢谢。

【问题讨论】:

    标签: c++ templates typetraits


    【解决方案1】:

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

    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 { };
    

    【讨论】:

      【解决方案2】:

      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
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-03
        • 1970-01-01
        • 2011-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-14
        相关资源
        最近更新 更多