我想创建名称空间Solids,该名称空间仅用于存储有关诸如platonic solids之类的几种常见实体的顶点和边/面连接性的信息。

所以我做了这个头文件Solids.h

#ifndef  Solids_h
#define  Solids_h

#include "Vec3.h" // this is my class of 3D vector, e.g. class Vec3d{double x,y,z;}

namespace Solids{

    struct Tetrahedron{
        const static int    nVerts = 4;
        const static int    nEdges = 6;
        const static int    nTris  = 4;
        constexpr static Vec3d verts [nVerts]    = { {-1.0d,-1.0d,-1.0d}, {+1.0d,+1.0d,-1.0d}, {-1.0d,+1.0d,+1.0d}, {+1.0d,-1.0d,+1.0d} };
        constexpr static int   edges [nEdges][2] = { {0,1},{0,2},{0,3}, {1,2},{1,3},{2,3} };
        constexpr static int   tris  [nTris ][3] = { {0,1,2},{0,1,3},{0,2,3},{1,2,3} };
    } tetrahedron;

};

#endif


然后在包含Solids.h的程序中,我要像这样绘制它:

void drawTriangles( int nlinks, const int * links, const Vec3d * points ){
    int n2 = nlinks*3;
    glBegin( GL_TRIANGLES );
    for( int i=0; i<n2; i+=3 ){
        Vec3f a,b,c,normal;
        convert( points[links[i  ]], a ); // this just converts double to float verion of Vec3
        convert( points[links[i+1]], b );
        convert( points[links[i+2]], c );
        normal.set_cross( a-b, b-c );
        normal.normalize( );
        glNormal3f( normal.x, normal.y, normal.z );
        glVertex3f( a.x, a.y, a.z );
        glVertex3f( b.x, b.y, b.z );
        glVertex3f( c.x, c.y, c.z );
    }
    glEnd();
};

// ommited some code there
int main(){
   drawTriangles( Solids::tetrahedron.nTris, (int*)(&Solids::tetrahedron.tris[0][0]), Solids::tetrahedron.verts );
}


但是,当我这样做时,我得到undefined reference to Solids::Tetrahedron::verts。可能与此undefined-reference-to-static-const-int问题有关。

因此,我猜解决方案应该类似于在namespace{}之外和struc{}声明之外进行初始化?

喜欢:

Solids::Tetrahedron::tris [Solids::Tetrahedron::nTris ][3] = { {0,1,2},{0,1,3},{0,2,3},{1,2,3} };


要么:

Solids::Tetrahedron.tris [Solids::Tetrahedron.nTris ][3] = { {0,1,2},{0,1,3},{0,2,3},{1,2,3} };


没有更优雅的解决方案了吗?

最佳答案

除了使用constexpr数据成员外,还可以使用constexpr静态成员函数。

struct Tetrahedron{
    constexpr static int    nVerts = 4;
    constexpr static int    nEdges = 6;
    constexpr static int    nTris  = 4;
    constexpr static Vec3d[nverts] verts() { return { {-1.0d,-1.0d,-1.0d}, {+1.0d,+1.0d,-1.0d}, {-1.0d,+1.0d,+1.0d}, {+1.0d,-1.0d,+1.0d} }; }
    constexpr static int[nEdges][2] edges() { return { {0,1},{0,2},{0,3}, {1,2},{1,3},{2,3} }; }
    constexpr static int[nTris ][3] tris() { return { {0,1,2},{0,1,3},{0,2,3},{1,2,3} }; }
} tetrahedron;

09-06 23:06