I'm trying to implement a constexpr find with c++17 to find the index of a matching element in an array (from cppreference) very similar to this question. Below is a very simple implementation with an int array.
namespace mine{
template<typename InputIter, typename T>
constexpr inline InputIter find(InputIter first, InputIter last, const T& val)
{
for(; first!=last; ++first)
if(*first == val) return first;
return first;
}
}
int main()
{
const std::array<int, 5> a{4, 10, 5, 889, 45};
auto b = mine::find(a.begin(), a.end(), 5);
auto c = std::distance(a.begin(), b);
return c;
}
The problem is GCC trunk is unable to deduce mine::find at compile time!! (live code mine::find).
However, simply by changing the switch to -std=c++2a (as c++20 marks std::find as constexpr), std::find gives me the expected results (live code std::find).
Edit: How can I get the same results as std::find with mine::find for the same optimization level without changing code in main()? (mind::find can of course be changed keeping a similar interface)
And what makes GCC optimize std::find better for the same optimization level?
Edit 2: Declaring b here as constexpr gives an error (live code with error)
int main()
{
const std::array<int, 5> a{4, 10, 5, 889, 45};
constexpr auto b = mine::find(a.begin(), a.end(), 5);
auto c = std::distance(a.begin(), b);
return c;
}
Note: Clang trunk seems to deduce mine::find correctly. But this has little to do with constexpr IMHO as clang deduces the result even without it.