代码之家  ›  专栏  ›  技术社区  ›  Yippie-Ki-Yay

C++型特征问题

  •  4
  • Yippie-Ki-Yay  · 技术社区  · 14 年前

    我想知道在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> ( 设施 是模板本身)。

    那么,有什么办法吗 (可能,肮脏,涉及丑陋的铸件,特定的对齐,任何可能工作的东西) 检查是否有 T 实际上等于一些 template type 不引入特定的空(辅助)基类(因为有时您根本不能)?

    谢谢您。

    2 回复  |  直到 13 年前
        1
  •  4
  •   sbi    13 年前

    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
    };
    
        2
  •  8
  •   Marcelo Cantos    14 年前

    你可以很容易地进行自己的测试:

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