模板中的T可以< typename T>使用继承? [英] Can T in template <typename T> use inheritance?

查看:180
本文介绍了模板中的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&

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 ,然后它会工作,无论 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;
    // ....
}

这篇关于模板中的T可以&lt; typename T&gt;使用继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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