[英]Partial template type deduction
我正在編寫一個模板,用於在編譯時指定的索引按元素對元組進行排序。 我有可行的代碼,但使用起來很痛苦,因為我必須指定用於對元組元素進行排序的二進制函數的類型。
template <typename BinaryFunction, int Index>
struct sort_by_index_t {
explicit sort_by_index_t(const BinaryFunction& binary_function)
: binary_function(binary_function) {}
template <typename Tuple>
bool operator()(const Tuple& left, const Tuple& right) const {
return binary_function(std::get<Index>(left),
std::get<Index>(right));
}
private:
const BinaryFunction binary_function;
};
template <typename BinaryFunction, int Index>
sort_by_index_t<BinaryFunction, Index>
sort_by_index(const BinaryFunction& binary_function) {
return sort_by_index_t<BinaryFunction, Index>(binary_function);
}
所以,如果我想按元組中的第一個元素排序,我必須輸入:
sort_by_index<std::less<char>, 0>(std::less<char>());
相反,我寧願有一個如下所示的接口,以避免重復,但它目前沒有編譯。
sort_by_index<0>(std::less<char>());
我沒有看到自動推斷Index
(並且沒有必要),但sort_by_index
應該能夠推斷出BinaryFunction
的類型。
如何重寫上面的內容,以便我不需要指定BinaryFunction
的類型?
Index
是不可扣除的,因此必須明確提供。 明確提供的模板參數只能從左到右提供,而模板參數的排序對於演繹無關緊要,因此只需對它們進行重新排序以確保Index
首先進行簡單修復:
template <int Index, typename BinaryFunction> // only this line needs to change
sort_by_index_t<BinaryFunction, Index>
sort_by_index(const BinaryFunction& binary_function) {
return sort_by_index_t<BinaryFunction, Index>(binary_function);
}
也就是說,這是令人不滿意的,因為我們正在混淆兩個看似無關的東西 - 我們用作比較器的二元函數,以及我們實際比較的數據。 我們必須在這里編寫很多代碼,這些代碼基本上只是重復的樣板。
在范圍提案中 ,Eric Niebler,Sean Parent和Andrew Sutton爭論采用可調整預測的算法。 如果您有一個C ++ 14編譯器,我建議您實現它們,以便您可以編寫如下內容:
// polymorphic getter
template <size_t I>
auto getter() {
return [](auto&& tuple) {
return std::get<I>(std::forward<decltype(tuple)>(tuple));
};
}
// just use the getter as a projection
std::sort(container_of_tuples,
std::less<char>{}, // this is the binary function
getter<0>()); // this is the projection
模板類型推導從右到左工作。 如果必須指定最右邊的模板參數,那么每個其他模板參數也必須如此。 以下對上述的略微修改允許更清晰的界面。 實質上, Index
模板參數必須在BinaryFunction
之前,因為sort_by_index
不能自動推導出Index
。
template <int Index, typename BinaryFunction>
struct sort_by_index_t {
explicit sort_by_index_t(const BinaryFunction& binary_function)
: binary_function(binary_function) {}
template <typename Tuple>
bool operator()(const Tuple& left, const Tuple& right) const {
return binary_function(std::get<Index>(left),
std::get<Index>(right));
}
private:
const BinaryFunction binary_function;
};
template <int Index, typename BinaryFunction>
sort_by_index_t<Index, BinaryFunction>
sort_by_index(const BinaryFunction& binary_function) {
return sort_by_index_t<Index, BinaryFunction>(binary_function);
}
下面現在編譯:
sort_by_index<0>(std::less<char>());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.