I start by saying that I am aware that what I am trying to do can easily be achieved trough the <functional> part of the library or trough a Functor or a Lambda, but I wanted to see this in template form.(Code below)
So the first function works, the find_if algorithm find the first value in a vector greater than the specified parameter, but there is no template argument deduction for that function call because the algorithm require a pointer to a function but at that time it is not know I will pass an int into it, and so I need to specify like this:
LargerThan_NoDeduction<30,int>
But this seems ugly because now I have to take care of match the two, like <31.2, double>, and the worst part is that if I now decide to pass something else, like a <'d',char> or a <-10,float> , the function expects a size_t as first argument, so this won't do.
So what I wanted to achieve was to pass a predicate to an algorithm in the form of
LargerThan(30)
where the template part of it takes care both of storing the data value (in this case 30, but could be a 'c') and deducing the type we compare from out of it, so in this case int.
So I have a function LargerThan(Type) that returns a function pointer and passes down the value to an helper function which takes both the value and the deduced type, so I don't have to type them myself.
Problem is, this helper function still has an auto in the first template parameter, and the compiler doesn't like this
How would you make this work trough template magics?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
////
template<size_t TestCase,typename Type>
bool LargerThan_NoDeduction(Type value)
{
return value > TestCase;
}
////
template<typename Type>
auto LargerThan(Type TestCase)-> bool(*)(Type)
{
return LargerThan_helper<TestCase, Type>;
}
template<auto TestCase, typename Type> //auto here is not liked!!!
bool LargerThan_helper(Type value)
{
return value > TestCase;
}
////
int main()
{
vector<int> vec{ 0,11,21,35,67,102 };
//Must specify size and type.
auto p = find_if(vec.begin(), vec.end(), LargerThan_NoDeduction<30,int>);//WORKS
if (p != vec.end()) { cout << *p << endl; }//WORKS
//Deduces type from the value passed.
p = find_if(vec.begin(), vec.end(), LargerThan(30));//ERROR
if (p != vec.end()) { cout << *p << endl; }//ERROR
return 0;
}
↧