使用Boost型特征条件编译 [英] Conditional Compile using Boost type-traits

查看:99
本文介绍了使用Boost型特征条件编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想这取决于参数的类型有条件地编译模板。我只在乎普通旧数据(POD),即整数等或类/结构之间的区别。我使用的是Windows上的C ++ VS2008。

I have a template that I would like to conditionally compile depending on the type of the argument. I only care about differentiating between "Plain Old Data" (POD), i.e., integers, etc or classes/structs. I'm using c++ VS2008 on Windows.

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

我一直在寻找Boost库的,我可以看到,他们似乎有我想要的东西。不过,我不明白的正确的语法#如果语句将是什么。

任何帮助将是AP preciated。

Any help would be appreciated.

编辑 -
阅读的响应后,我看到了我在这个问题的定义忽略了什么。类是一个模板类,只需要实例这是正确的类类型T 。我一直在寻找能解决的编译时的解决方案。希望这清除了我的问题。

Edit --- After reading the responses, I see I overlooked something in my definition of the question. Class foo is a templated class that only needs to instance the version of bar that is correct for class type T. I was looking for a solution that can be resolved a compile time. Hope this clears up my problem.

推荐答案

您可以不用 enable_if ,因为所有你需要的是根据类型特征派遣。 enable_if 用于从重载添加/删除模板实例来/。您可能需要使用呼叫特性选择最佳的方法将对象传递给你的函数。作为一项规则,对象应该通过引用传递,而POD是按值传递。 call_traits 让你的常量非const 引用之间进行选择的。在code以下使用常量引用。

You can do it without enable_if, because all you need is to dispatch depending on type traits. enable_if is used to add/remove template instantiations to/from overload resolution. You may want to use call traits to choose the best method to pass objects to your function. As a rule, objects should be passed by reference, whereas POD is passed by value. call_traits let's you choose between const and non-const references. The code below uses const reference.

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

这篇关于使用Boost型特征条件编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆