【发布时间】:2012-05-22 15:57:44
【问题描述】:
在一个项目中,我有几个类,其中封装了作为静态数组实现的矩阵,例如:
struct StaticContainer
{
static const short e[2][4];
};
/// Initialize components of member-array (with external linkage).
const short StaticContainer::e[2][4] = {
{ -1, 0, 0, 1 },
{ 0, -1, 1, 0 }
};
我想实现一个提供反向映射的元函数,从 StaticContainer::e 中的列返回到第二个索引(在本例中为 1-4)。理想情况下,是这样的:
template< typename TContainer, short TeX, short TeY >
struct VectorToIndex
{
enum { value = ??? };
};
最后,我想通过(如果这可能的话):
BOOST_STATIC_ASSERT( 0 == VectorToIndex< StaticContainer, -1, 0 >::value );
这可能吗?我最初尝试递归搜索'e'矩阵失败了,因为每当我尝试访问(在编译时)我得到的条目(GCC):
error: ‘StaticContainer::e’ cannot appear in a constant-expression
我应该明白矩阵中的值在编译时不可用吗?
我会很感激任何 cmets。我可以随意更改矩阵的初始化/存储方式(所以我在考虑一些编译时注册机制)。唯一的限制是在编译时获得这种反向映射。
说明:
e-matrix 中的每一列代表一个空间方向(在本例中为 2D)。这些列保证是不同的。
-
我希望元函数的结果如下:
VectorToIndex< StaticContainer, -1, 0 > --> '0' at compile-time VectorToIndex< StaticContainer, 0,-1 > --> '1' at compile-time VectorToIndex< StaticContainer, 0, 1 > --> '2' at compile-time VectorToIndex< StaticContainer, 1, 0 > --> '3' at compile-time
如果这个模板是用无效的数字组合实例化的(即它不是矩阵中的一列),我想产生一个编译错误。
- 我目前拥有的解决方案是一个简单的程序,它手动编写带有必要模板实例的文件。这满足了要求(结果是正确的,并且对于无效向量存在编译时错误 - 因为缺少相应的模板实例化)。但是,由于我的代码库中有许多类似于“StaticContainer”的类(其中许多具有较大的矩阵),因此此过程会生成数千行代码:(。
【问题讨论】:
-
你不能使用mpl?如果您可以将数组中的值定义为整数常量,那么您可以使用现有的
boost::mpl::vector可能吗? -
我会调查的。你知道是否可以在 boost::mpl::vector 中存储一个矩阵(如 std::vector<:vector>>?)
-
@Dragos:你能否更好地定义逆映射,如果我提供
(0, 0)作为参数呢?1和2都是有效的索引。 -
@MatthieuM.:感谢您的关注。我添加了一些说明。
-
如果您可以访问实现此功能的编译器,也可以使用可变参数模板来解决此问题。当我今晚晚些时候回到家时,我会试着告诉你怎么做,也就是说,如果在那之前没有其他人这样做的话。从那里开始,如果需要符合 c++03 标准,通过 mpl 增强它应该不难,尽管我必须说我自己从未真正使用过 mpl。
标签: c++ metaprogramming template-meta-programming