'Why can't I pass operator to a function from an other in C++?
In my C++ homework (where I have to short different arrays with different methods), I run into a problem. I can't pass comp() from one function to another.
Here is a simplified version of my code:
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;
}
At the moment I am getting:
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]|
What would be the correct way to solve this?
Solution 1:[1]
The problem is that you're passing comp() as the last argument instead of passing comp.
To solve this pass comp instead of comp() as shown below:
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);
}
Moreover, before using a function you should have a declaration for that function. See in the working demo linked above.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anoop Rana |
