updated带有可变版本
1. 简单、明确的代码
class MyClass {
public:
vector<vector<vector<MapCell>>> m;
MyClass(int size_x, int size_y, int size_z)
: m(size_x,
vector<vector<MapCell> >(
size_y,
vector<MapCell>(size_z)
)
) {
}
};
2. 有帮手
class MyClass {
vector<vector<vector<MapCell>>> m;
public:
MyClass(int size_x, int size_y, int size_z)
: m(Dim(size_z, Dim(size_y, Dim(size_x, MapCell())))) {
}
private:
template <typename T>
static std::vector<T> Dim(size_t n, T&& v) {
return std::vector<T>(n, std::move(v));
}
};
3. 使用可变参数助手
Because 可变参数是 funadic! http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Variadic-Templates-are-Funadic这是一个使用变量使事情变得更漂亮的版本(取决于品味):
struct MyClass
{
vector<vector<vector<MapCell>>> m;
MyClass(int size_x, int size_y, int size_z)
: m(vec_matrix(MapCell(), size_z, size_y, size_x))
{ }
private:
template <typename T> static std::vector<T> vec_matrix(T v, size_t n) {
return { n, std::move(v) };
}
template <typename T, typename... Dim> static auto vec_matrix(T v, size_t n, Dim... other)
-> std::vector<decltype(vec_matrix(v, other...))> {
return { n, vec_matrix(v, other...) };
}
};
PS。我稍微编辑了代码以使其更符合标准。模板有一个微妙的问题尾随返回类型 http://en.wikipedia.org/wiki/C%2B%2B11#Alternative_function_syntax指的是同名的重载。
有关此处问题的详细分析,请参阅聊天中的此讨论书签 https://chat.stackoverflow.com/rooms/10/conversation/latereturntype-and-variadics
如果您的编译器不认为它应该工作,请查看它住在 gcc 4.7.2 上 http://liveworkspace.org/code/d72e6a6134dbfe5aebbc32bd06a685c0. 它仅使用 boost 来格式化输出:
. . . .
. . . .
. . . .
. . . .
. . . .
-------
. . . .
. . . .
. . . .
. . . .
. . . .
避免链接腐烂的完整代码:
#include <iostream>
#include <vector>
#include <boost/spirit/include/karma.hpp> // for debug output only
using namespace std;
struct MapCell
{
friend std::ostream& operator <<(std::ostream& os, MapCell const&)
{ return os << "."; }
};
struct MyClass
{
vector<vector<vector<MapCell>>> m;
MyClass(int size_x, int size_y, int size_z)
: m(vec_matrix(MapCell(), size_z, size_y, size_x))
{ }
private:
///////////////////////////////////////////////////
// variadics are funadic!
template <typename T> static std::vector<T> vec_matrix(T v, size_t n)
{
return { n, std::move(v) };
}
template <typename T, typename... Dim> static auto vec_matrix(T v, size_t n, Dim... other)
-> std::vector<decltype(vec_matrix(v, other...))>
{
return { n, vec_matrix(v, other...) };
}
////////////
};
int main()
{
MyClass a(4,5,2);
using namespace boost::spirit::karma;
std::cout
<< format(stream % ' ' % eol % "\n-------\n", a.m)
<< std::endl;
}