【发布时间】:2012-11-27 01:43:27
【问题描述】:
我正在尝试编写类似 here 的代码,但使用的是 C++11 功能,没有 Boost。
从this example 开始工作,我尝试定义一个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 ) ;
}
【问题讨论】:
-
您能否让您的问题独立并描述您想要实现的目标?
-
它是独立的。
#ifT有一个.normal成员,response_traithas_normal应该为真,并且应该选择正确的编译路径。 -
除非我完全误解了类型特征。链接的问题是我的出发点,但我不知道我是否采取了错误的方式。
-
您不能为此使用预处理器指令,因为特征是 C++ 编译时概念,根本不涉及预处理器。
-
另外,您可以直接将en.cppreference.com/w/cpp/types/is_same 与 VertexN 一起使用。
标签: c++ conditional-compilation typetraits