Pas*_*van 2 c++ templates variadic-templates c++11
我觉得有趣的是这个类型特征与std :: array不匹配(它给出了编译错误),但它适用于unordered_map.这是为什么?
#include <iostream>
#include <unordered_map>
#include <array>
template <typename T, template <typename...> class Ref>
struct is_specialization : std::false_type {
};
template <template <typename...> class Ref, typename... Args>
struct is_specialization<Ref<Args...>, Ref> : std::true_type {
};
int main()
{
using T = std::unordered_map<int, int>;
using C = std::array<int, 2>;
auto value = is_specialization<T, std::unordered_map>::value;
std::cout << "Is type of unorderd map specialization? : " << std::boolalpha << value << std::endl;
auto secondValue = is_specialization<C , std::array>::value;
std::cout << "Is type of array specialization? : " << std::boolalpha << secondValue << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
您的主模板有两个参数:一个类型参数和一个模板模板参数,其模板参数都是以下类型:
template <typename T, template <typename...> class Ref>
struct is_specialization;
Run Code Online (Sandbox Code Playgroud)
std::array 是一个类模板,是的,但它的模板参数不是所有类型:
template<
class T,
std::size_t N // <== not a type
> struct array;
Run Code Online (Sandbox Code Playgroud)
任何不属于类型的东西都是模板元编程领域的二等公民.这只是值得吸吮的一个例子.
如果您编写了自己的array包装器,它确实采用了两种类型:
template <typename T, typename N>
struct my_array : std::array<T, N::value> { };
Run Code Online (Sandbox Code Playgroud)
那么你可以像你期望的那样使用你的特质:
using C = my_array<int, std::integral_constant<int, 2>>;
auto secondValue = is_specialization<C , my_array>::value; // true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |