template <typename A, typename B, typename... C>
struct index_of
{
static constexpr int const value =
std::is_same<A, B>{}
? 0
: (index_of<A, C...>::value >= 0) ? 1+index_of<A, C...>::value : -1;
};
template <typename A, typename B>
struct index_of<A, B>
{
static constexpr int const value = std::is_same<A, B>{} -1;
};
は からへstd::is_same<A, B>{} -1
の変換を使用することに注意してください。bool
int
から派生することでより良いintegral_constant
:
template <typename A, typename B, typename... C>
struct index_of
: std::integral_constant
< int,
std::is_same<A, B>{}
? 0
: (index_of<A, C...>{} == -1 ? -1 : 1+index_of<A, C...>{})
>
{};
template <typename A, typename B>
struct index_of<A, B>
: std::integral_constant < int, std::is_same<A, B>{} -1 >
{};
タイプが見つからない場合に戻る必要がない-1
場合: (誰かがstatic_assert
ここにかなりの診断メッセージを組み込む方法を知っている場合は、コメント/編集をいただければ幸いです)
template <typename A, typename B, typename... C>
struct index_of
: std::integral_constant < std::size_t,
std::is_same<A, B>{} ? 0 : 1+index_of<A, C...>{} >
{};
template <typename A, typename B>
struct index_of<A, B>
: std::integral_constant<std::size_t, 0>
{
constexpr operator std::size_t() const
{
return std::is_same<A, B>{}
? 0
: throw std::invalid_argument("Type not found!");
}
};