我目前正在尝试为列表实现编写一个长度元函数,我已经写过但有一些问题。这是我目前的实施:
#include <iostream>
#include <type_traits>
template <typename T, T N>
struct type_ {
using type = type_<T, N>;
using value_type = T;
static constexpr T value = N;
using next = type_<T, N + 1>;
using prev = type_<T, N - 1>;
};
template <int N>
struct int_ : type_<int, N> {
using type = int_<N>;
};
struct empty {
using type = empty;
using value = empty;
};
template <typename car, typename cdr>
struct cons {
using type = cons<car, cdr>;
using value = car;
using next = cdr;
};
struct cdr_f {
template <typename cons>
struct apply {
using type = typename cons::next::type;
};
};
template <typename cons>
struct cdr : cdr_f::template apply<cons> {};
struct car_f {
template <typename cons>
struct apply {
using type = typename cons::type::value;
};
};
template <typename cons>
struct car : car_f::template apply<cons> {};
struct length_f {
template <typename list>
struct apply : std::conditional<
std::is_same<typename car<list>::type, empty>::value,
int_<0>,
int_<1 + length_f::template apply<typename cdr<list>::type>::value>
> {};
};
int main() {
std::cout << std::is_same<
typename car<empty>::type,
empty
>::value << std::endl; // prints 1.
std::cout << length_f::template apply<empty>::type::value << std::endl; // should print 0.
return 0;
}
应用length_f::template apply<empty>
时出现以下错误:
错误:没有名为&#39; next&#39; in&#39; meta :: list :: empty&#39;
我已经在这里呆了几个小时了,我认为发生的事情是由于某种原因std::is_same<typename car<list>::type, empty>::value
正在返回false,但是做一些测试似乎在评估{{1时}}。预期car<empty>::type
返回编译器错误,但由于条件已到位,它不应该能够达到该点。
如果有帮助,我会使用Apple的clang-602.0.53。
感谢。