在我的 C 作業中(我必須用不同的方法縮短不同的陣列),我遇到了一個問題。我不能將 comp() 從一個函式傳遞到另一個函式。
這是我的代碼的簡化版本:
template <typename T, typename Compare = std::less<T>>
void fooFunction(T arr[], int arraySize, Compare comp = Compare{})
{
int endElem=arraySize-1;
int beginElem =0;
fooFunction2(arr, beginElem , endElem, arraySize, comp()); //I am getting the errors here
}
template <typename T, typename Compare = std::less<T>>
void fooFunction2(T arr[], int beginElem, int endElem, int arraySize, Compare comp = Compare{})
{
}
struct string_size_less
{
bool operator()(const std::string &a, const std::string &b) const
{
return a.size() < b.size();
}
};
int main()
{
int arrI[] = { 4, 5, 1, 4, 2};
std::string arrS[] = {"Car", "Bicycle", "Metro", "Bike"};
fooFunction(arrI, 5);
fooFunction(arrS, 4, string_size_less());
return 0;
}
目前我得到:
error: no match for call to '(std::less<int>) ()'|
error: 'fooFunction2' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]|
解決這個問題的正確方法是什么?
uj5u.com熱心網友回復:
我改變了兩件事:
在你的電話中
fooFunction2(..),不要通過comp()但是comp。如果添加括號,則執行 comp 函式,該函式失敗,因為比較函式需要傳遞給它的引數。只是傳遞comp只會告訴它在哪里尋找有問題的函式。將
fooFunction2(..)上面的定義放在你呼叫它的地方。如果您稍后定義它,編譯器將不會在它找到第一次呼叫它的那一刻找到定義。(可能有編譯器選項來解決這個問題)。只需交換定義就足以修復它,盡管在頭檔案中宣告它(尤其是在較大的專案中)可能是一種更順暢的方式。這段代碼編譯得很好:template <typename T, typename Compare = std::less<T>> void fooFunction2(T arr[], int beginElem, int endElem, int arraySize, Compare comp = Compare{}) { } template <typename T, typename Compare = std::less<T>> void fooFunction(T arr[], int arraySize, Compare comp = Compare{}) { int endElem=arraySize-1; int beginElem =0; fooFunction2(arr, beginElem , endElem, arraySize, comp); //I am getting the errors here } struct string_size_less { bool operator()(const std::string &a, const std::string &b) const { return a.size() < b.size(); } }; int main() { int arrI[] = { 4, 5, 1, 4, 2}; std::string arrS[] = {"Car", "Bicycle", "Metro", "Bike"}; fooFunction(arrI, 5); fooFunction(arrS, 4, string_size_less()); return 0; }
uj5u.com熱心網友回復:
問題是您comp()作為最后一個引數傳遞而不是傳遞comp.
解決這個passcomp而不是comp()如下圖:
struct string_size_less
{
bool operator()(const std::string &a, const std::string &b) const
{
return a.size() < b.size();
}
};
template <typename T, typename Compare = std::less<T>>
void fooFunction2(T arr[], int beginElem, int endElem, int arraySize, Compare comp = Compare{})
{
}
template <typename T, typename Compare = std::less<T>>
void fooFunction(T arr[], int arraySize, Compare comp = Compare{})
{
int endElem=arraySize-1;
int beginElem =0;
//----------------------------------------------------vvvv--->changed from comp() to comp
fooFunction2(arr, beginElem , endElem, arraySize, comp);
}
作業演示
此外,在使用函式之前,您應該有該函式的宣告。請參閱上面鏈接的作業演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/479757.html
