这样的事情有可能存在吗?是否有可能在C++中开发静态循环?
template<int Channel>
void deduce_mask(Matrix const &src, int mask[])
{
//I hope i could become a constant and the compiler would unroll the loop at compile time
for(int i = Channel; i != -1; --i)
{
//mapper is a helper class which translate two and three dimension into one dimension index
//constexpr makes it possible to find out the index at compile time
mask[mapper(0, 1, i)] = src(row - 1, col)[i];
mask[mapper(1, 1, i)] = src(row, col)[i];
mask[mapper(2, 1, i)] = src(row + 1, col)[i];
}
}
代替
template<int Channel>
class deduceMask
{
public:
static void deduce_mask(matrix const &src, int mask[]);
};
template<int Channel>
void deduce_mask(matrix const &src, int mask[])
{
mask[mapper(0, 1, Channel)] = src(row - 1, col)[Channel];
mask[mapper(1, 1, Channel)] = src(row, col)[Channel];
mask[mapper(2, 1, Channel)] = src(row + 1, col)[Channel];
deduceMask<Channel - 1>::deduce_mask(src, mask);
}
template<>
class deduceMask<-1>
{
public:
static void deduce_mask(matrix const &src, int mask[])
{
}
};
第二种解决方案是唯一的解决办法我能想出的时候我想的编译器来找出 在编译time.Do结果我有一个简单的方法来使“i”变成恒定值,如 元编程解决方案?对我来说,一个简单的for循环更容易处理,而不是元编程版本的 。
对不起,我可怜的英语,我希望我能正确解释我的问题。
你也可以递归地编写它并使用constexpr,如果你喜欢这种类型的语法? – Agentlien
我试图做一个constexpr版本但失败,constexpr只允许一个return语句。 – StereoMatching
我相当肯定,大多数现代编译器会自动执行这种优化,就像他们为'for'循环执行直到一个常量值(例如'for(int i = 0; i <5; i ++)')一样。你必须检查确定。 – ShdNx