我正在尝试编写类似此处的代码,但使用 C++11 功能,而不使用 Boost。
从这个例子开始,我试图定义一个response_trait
基于特征结果的条件编译。我怎样才能使这项工作?
#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 ) ;
}