I am defining a way to know the position of the type in a type list, using recursive templates in C++17. I tried two ways : one using constexpr value and one using constexpr function. The second, using if
statement, compiles, while the first, using ternary operator, does not compile.
#include <type_traits>
#include <iostream>
template<typename Searching, typename First, typename...Others>
constexpr std::size_t index_of = std::is_same_v<Searching,First> ? 0 : 1 + index_of<Searching,Others...>;
template<typename Searching, typename First, typename...Others>
constexpr std::size_t IndexOf() {
if constexpr(std::is_same_v<Searching,First>)
return 0;
else return 1 + IndexOf<Searching,Others...>();
};
int main() {
std::cout << index_of<int, int> << std::endl; //does not compile
std::cout << IndexOf<int, int>() << std::endl; //compile
//both should return 0
return 0;
}
My compiler, migw64, says :
wrong number of template arguments (1, should be at least 2)
constexpr std::size_t index_of = std::is_same_v<Searching,First> ? 0 : 1 + index_of<Searching,Others...>;
From what I understand, the ternary operator needs to evaluate its two operands, so it can not be used in this type of recursion.
Am I right ? and if yes, why is it like that ?
Thank you.