假设我需要创建一个接受新类型的类型,就像容器的工作方式一样。
如果没有 Push_back 类型使用模板专业化,我可以实现同样的事情吗?
#include <iostream>
template <typename...>
struct type_list {};
template <typename T>
struct my_type { using type = T; };
template <typename LIST, typename T>
struct push_back;
template <typename... Args, typename T>
struct push_back<type_list<Args...>, T> : my_type<type_list<Args..., T>>
{
};
template <typename LIST, typename T>
using push_back_t = typename push_back<LIST, T>::type;
int main()
{
type_list<int, bool> x;
push_back_t<decltype(x), float> y;
type_list<int, bool,float> z;
std::cout << std::is_same_v<decltype(y), decltype(z)> << '\n';
}
Run Code Online (Sandbox Code Playgroud) 我很喜欢学习元编程,并开始了解一些功能,但我无法调用 at Works,它需要一个索引来返回映射到可变位置的类型。
#include <iostream>
#include <type_traits>
#include <utility>
template <typename...>
struct type_list {};
template<typename T ,typename... Ns>
auto pop_front(type_list<T, Ns...> t) {
return type_list<Ns...>{};
}
template<typename T ,typename... Ns>
auto front(type_list<T, Ns...> t)
{
return type_list<T>{};
}
template<typename T ,typename... Ns>
auto at(type_list<T, Ns...> t, size_t i)
{
if (i) return at(pop_front(t), i-1);
return front(t);
}
int main()
{
type_list<int, bool, float> x;
at(x,2);
}
Run Code Online (Sandbox Code Playgroud)