【问题标题】:Pass container value_type as template parameter?将容器 value_type 作为模板参数传递?
【发布时间】:2013-04-11 15:07:50
【问题描述】:

是否可以将容器的 value_type 作为模板参数传递?

类似:

template<typename VertexType>
class Mesh
{
    std::vector<VertexType> vertices;
};

std::vector<VertexPositionColorNormal> vertices;

// this does not work, but can it work somehow?
Mesh<typename vertices::value_type> mesh;

// this works, but defeats the purpose of not needing to know the type when writing the code
Mesh<typename std::vector<VertexPositionColorNormal>::value_type> mesh;

在创建网格(第一个)时,我得到一个“无效的模板参数”,但它应该可以正常工作吗?我在编译时传递了一个已知类型,为什么它不起作用?有什么替代品?

谢谢。

【问题讨论】:

    标签: c++ templates stl


    【解决方案1】:

    在 C++11 中你可以使用decltype:

        Mesh<decltype(vertices)::value_type> mesh;
    //       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    一个完整的编译示例是:

    #include <vector>
    
    struct VertexPositionColorNormal { };
    
    template<typename VertexType>
    class Mesh
    {
        std::vector<VertexType> vertices;
    };
    
    int main()
    {
        std::vector<VertexPositionColorNormal> vertices;
    
        Mesh<decltype(vertices)::value_type> mesh;
    //       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
    

    Live example.

    另一方面,如果你仅限于 C++03,你能做的最好的可能就是定义一个类型别名:

    int main()
    {
        std::vector<VertexPositionColorNormal> vertices;
    
        typedef typename std::vector<VertexPositionColorNormal>::value_type v_type;
    
        // this does not work, but can it work somehow?
        Mesh<v_type> mesh;
    }
    

    【讨论】:

    • 非常感谢,它工作得很好。我想我得读一下关于 decltype 的内容。现在无法接受答案(说我需要等待 6 分钟),但稍后会接受。非常感谢!
    • @sap:很好,很高兴它有帮助:)
    猜你喜欢
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    相关资源
    最近更新 更多