您如何使用类型特征进行条件编译? [英] How do you use type traits to do conditional compilation?

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

问题描述

我正在尝试在此处编写代码,但使用C + +11个功能,没有Boost。

I'm trying to write code like here but using C++11 features, without Boost.

此示例中工作 ,我尝试定义 response_trait ,并根据特征的结果进行条件编译。我该如何进行这项工作?

Working from this example, I tried to define a response_trait, and basee conditional compilation on the result of the trait. How can I make this work?

#include <vector>
using namespace std ;

struct Vector{ float x,y,z ; } ;
struct Vertex { Vector pos ; } ;
struct VertexN { Vector pos, normal ; } ;
struct Matrix {} ;

template <typename T>
struct response_trait {
  static bool const has_normal = false;
} ;

template <>
struct response_trait<VertexN> {
  static bool const has_normal = true;
} ;

template <typename T>
struct Model
{
  vector<T> verts ;

  void transform( Matrix m )
  {
    for( int i = 0 ; i < verts.size() ; i++ )
    {
      #if response_trait<T>::has_normal==true
      puts( "Has normal" ) ;
      // will choke compiler if T doesn't have .normal member
      printf( "normal = %f %f %f\n", verts[i].normal.x, verts[i].normal.y, verts[i].normal.z ) ;
      #else
      puts( "Doesn't have normal" ) ;
      printf( "pos = %f %f %f\n", verts[i].pos.x, verts[i].pos.y, verts[i].pos.z ) ;
      #endif
    }
  }

} ;

int main()
{
  Matrix m ;
  Model<Vertex> model ;
  model.verts.push_back( Vertex() ) ;
  model.transform( m ) ;

  Model<VertexN> modelNormal ;
  modelNormal.verts.push_back( VertexN() ) ;
  modelNormal.transform( m ) ;
}


推荐答案

您可以尝试类似的方法:

You could try something like this:

void transform_impl(Matrix const & m, std::true_type const &)
{
    // has normal
}

void transform_impl(Matrix const & m, std::false_type const &)
{
    // doesn't have normal
}

template <typename T>
void transform(Matrix const & m)
{
    transform_impl(m, response_trait<T>());
}

您只需要稍微修改一下特征:

You just need to modify your trait a bit:

#include <type_traits>
template <typename> struct response_trait : std::false_type { };
template <> struct response_trait<VertexN> : std::true_type { };

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

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