【发布时间】:2018-10-21 10:01:42
【问题描述】:
我想在编译期间检查一个类型是否是特定模板的实例化。
例如:
-
std::vector<int>是std::vector的实例化 -
std::array<int, 5>是std::array的实例化
我可以进行适用于案例 1 但不适用于案例 2 的测试。
#include <iostream>
#include <type_traits>
#include <string>
#include <vector>
#include <array>
#include <queue>
template<template<typename...> class, typename...>
struct is_instantiation : public std::false_type {};
template<template<typename...> class U, typename... T>
struct is_instantiation<U, U<T...>> : public std::true_type {};
int main() {
using A = std::vector<int>;
std::cout << is_instantiation<std::vector, A>::value << "\n";
std::cout << is_instantiation<std::queue, A>::value << "\n";
// std::cout << is_instantiation<std::array, A>::value << "\n";
}
如何使它适用于这两种情况?
我试过自动,但不能让它工作。
【问题讨论】:
-
如果你只对 STL 容器类型感兴趣,你将不得不为数组做一个特殊的案例——据我所知,它是唯一接受非类型模板参数的模板容器。如果您对 any 模板感兴趣,我看不出有什么方法可以使它工作,因为类型和非类型模板没有通用语法。