這樣的事情有可能存在嗎?是否有可能在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