是否可以将容器的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;
Run Code Online (Sandbox Code Playgroud)
我在创建网格(第一个)时得到"无效的模板参数",但是它应该正常工作吗?我在编译时传递一个已知类型,为什么它不起作用?有什么替代品吗?
谢谢.
在C++ 11中,您可以使用decltype:
Mesh<decltype(vertices)::value_type> mesh;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
一个完整的编译示例是:
#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;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
Run Code Online (Sandbox Code Playgroud)
实例.
另一方面,如果您仅限于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;
}
Run Code Online (Sandbox Code Playgroud)