模板中的T可以< typename T>使用继承?
我想做这样的事情:
template <typename T:public Vertex> addTri( T v1, T v2, T v3 )
{
// Take v1.pos, v2.pos, v3.pos and create a geometric repn..
Triangle tri( v1.pos, v2.pos, v3.pos ) ; // all vertices will
// have to have a .pos member.
// Create the vertex buffer..
VertexBuffer<T> vb ...
}
由于这不起作用,这是我的解决方法。 。
Since that doesn't work, this is my workaround..
template <typename T> addTri( T v1, T v2, T v3 )
{
Vertex* p1 = (Vertex*)&v1 ;
// This is a very "shut up C++, I know what I'm doing" type cast.
// I'd like for C++ to know that all vertex types (T in this case)
// __will__ have a Vector member .pos.
Triangle tri( p1->pos, p2->pos, p3->pos ) ;
// Create the vertex buffer..
VertexBuffer<T> vb ...
}
背景
如果您感兴趣,我正在尝试编写一些代码来处理三角形创建。
每个顶点都必须有一个 .pos
成员,因为每个顶点都必须有一个空格位置。
Background
In case you're interested, I'm trying to write a general bit of code to handle triangle creation.
Each vertex has to have a .pos
member, because each vertex has to have a position in space.
然而,并非每个顶点类型都具有纹理坐标。并非每个顶点都有颜色。因此参数化类型。
However not every vertex type will have a texture coordinate. Not every vertex will have a color. Hence the parameterized types.
在XNA中使用了类似的方法 VertexBuffer.SetData< T>
。
A similar approach is used in XNA VertexBuffer.SetData<T>
.
您无法在模板类型参数中指定类型限制。但是,通常情况下,您不需要。
You cannot specify a type restriction in the template type argument. However, generally, you don't have to.
如果您只是这样做:
template <typename T> addTri( T v1, T v2, T v3 )
{
Vertex &v1r = v1;
// ....
}
这将有效用Vertex的导数实例化。如果 T&
不可转换为 Vertex& $ c $,它会产生(模糊)错误c>。
This will work if the function is instantiated with a derivative of Vertex. It will create an (obscure) error if T &
is not convertible to Vertex &
.
如果您甚至不关心这些类型是否可转换为 Vertex
,只要它们有相同的成员,你甚至可以跳过作业 - C ++模板参数基本上使用鸭子打字;如果您执行 v1.x
,并且 T
包含名为 x $ c的成员$ c>,然后它会工作,无论
T
可能实际上是什么类型。
If you don't even care if the types are convertible to Vertex
as long as they have the same members, you can even skip the assignment - C++ template arguments essentially work using duck typing; if you do v1.x
, and T
contains a member named x
, then it will work, whatever type T
might actually be.
你可以多一点使用boost的类型特征库进行复杂化和静态断言;有了这个,你可以开始定义一个断言,使错误更容易理解:
You can be a bit more sophisticated using boost's type-traits library and a static assertion; with this, you can start defining an assertion to make the error a bit easier to understand:
template <typename T> addTri( T v1, T v2, T v3 )
{
BOOST_STATIC_ASSERT_MSG(boost::is_convertible<T&, Vertex&>::value,
"Template argument must be a subclass of Vertex");
Vertex &v1r = v1;
// ....
}