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

使用Boost类型特征的条件编译

  •  7
  • photo_tom  · 技术社区  · 15 年前

    template<T>
    class foo
    {
        void bar(T do_something){
        #if IS_POD<T>
            do something for simple types
        #else
            do something for classes/structs
        #endif
    }}
    

    #if 声明应该是。

    任何帮助都将不胜感激。


    在阅读了回答之后,我发现我在对问题的定义中忽略了一些东西。等级 foo 是一个模板化类,它只需要实例 bar 这是正确的 class type T

    3 回复  |  直到 15 年前
        1
  •  7
  •   user401947    15 年前

    启用\u if ,因为您只需要根据类型特征进行分派。 启用\u if 用于在重载解析中添加/删除模板实例化。您可能需要使用调用特征来选择将对象传递给函数的最佳方法。通常,对象应该通过引用传递,而POD是通过值传递的。 让你在两者之间做出选择 常数 非常量 参考文献。下面的代码使用 常数 参考文献。

    #include <boost/type_traits.hpp>
    #include <boost/call_traits.hpp>
    
    template <typename T>
    class foo {
    public:
        void bar(typename boost::call_traits<T>::param_type obj) {
            do_something(obj, boost::is_pod<T>());
        }
    private:
        void do_something(T obj, const boost::true_type&)
        {
          // do something for POD
        }
        void do_something(const T& obj, const boost::false_type&)
        {
          // do something for classes
        }
    };
    
        2
  •  3
  •   sbi    15 年前

    假设 IsPod<T>::result 返回相似的内容 Boolean<true> / Boolean<false> :

    template<T>
    class foo
    {
        void do_something(T obj, Boolean<true> /*is_pod*/)
        {
          // do something for simple types
        }
        void do_something(T obj, Boolean<false> /*is_pod*/)
        {
          // do something for classes/structs
        }
    
        void bar(T obj)
        {
           do_something(obj, IsPod<T>::result());
        }
    }
    
        3
  •  0
  •   doublep    15 年前

    Boost Enable If library 相反。

    具体来说,在您的情况下,它看起来像(未测试):

    void bar (typename enable_if <is_pod <T>, T>::type do_something)
    {
        // if is POD
    }
    
    void bar (typename disable_if <is_pod <T>, T>::type do_something)
    {
        // if not
    }