代码之家  ›  专栏  ›  技术社区  ›  Philipp

如果模板类型是可实例化的,则执行某些操作

  •  2
  • Philipp  · 技术社区  · 15 年前

    //Only instantiable with types T for which T.x() is ok:
    template <class T>
    class TemplateClass
    {
      T t;
    public:
      void foo() { 
        t.x(); 
      }
    }
    
    template <class T>
    class User
    {
      void foo()
      { 
        "if TemplateClass<T> is ok then do something else do nothing" 
      }
    }
    

    我怎么能那样做?

    谢谢!

    template <class T>
    struct TemplateClass
    {
        T t;
        void foo() { t.x(); }
    
        static const bool value = true;
    
    };
    struct A {};
    struct B { void x() {} };
    
    template <class T>
    struct User
    {
        template<typename M>
        typename boost::enable_if<TemplateClass<M> >::type func( ) 
        { 
            std::cout << "enabled\n";
        }
    
        template<typename M>
        typename boost::disable_if<TemplateClass<M> >::type func( ) 
        { 
            std::cout << "disabled\n";
        }
    
    
        void foo()
        {
            func<TemplateClass<T> >();
        }
    
    };
    
    User<A> a;
    a.foo();
    
    User<B> b;
    b.foo();
    

    但这将返回“enabled enabled”。我错过了什么?

    1 回复  |  直到 15 年前
        1
  •  1
  •   edA-qa mort-ora-y    15 年前

    你应该看看提振 boost/utility/enable_if.hpp

    这里最简单的方法是有两个版本的foo函数,都是模板函数。其中一个函数将使用enable_if构造,另一个函数将使用disable_if构造。

    我相信你可以在boost网站上找到更好的例子,但是像这样的:

    template<typename M>
    typename boost::enable_if<Template<M>>::type func( ) { }
    

    template<typename M>
    typename boost::disable_if<Template<M>>::type func( ) { }
    

    我不确定您是否可以在一个模板内,在此模式中定义两个成员函数,而不使它们同时成为模板函数。我想您可以定义这两个模板函数并将默认模板参数设置为T。