检查两种类型是否属于同一模板 [英] Check if two types are of the same template
问题描述
我想检查两种类型是否属于同一模板。例如,我希望下面的代码片段返回 true
,因为尽管内部元素的类型不同,但两个对象都是向量。
I want to check if two types are of the same template. As an example I want the following snippet of code to return true
because both objects are vectors despite the inner elements being of different types.
在编译时进行检查很重要(这就是该函数为constexpr的原因)。
It's important that the check is made at compile time (that's why the function is constexpr).
#include <iostream>
#include <type_traits>
#include <vector>
template <typename Container1, typename Container2> constexpr bool CheckTypes(Container1 c1, Container2 c2)
{
return std::is_same<Container1,Container2>::value;
}
int main()
{
std::vector<int> v1(100,0);
std::vector<double> v2(100,0);
std::cout << CheckTypes(v1,v2);
}
推荐答案
在这里:
template <class T, class U>
struct are_same_template : std::is_same<T, U>
{};
template <template<class...> class T, class T1, class T2>
struct are_same_template<T<T1>, T<T2>> : std::true_type
{};
template <class T, class U>
constexpr bool CheckTypes(T, U)
{
return are_same_template<T, U>::value;
}
演示: http://coliru.stacked-crooked.com/a/8533c694968f4dbb
这是通过提供 are_same_template
的特化来工作的,它放弃了模板参数类型:
This works by providing a specialization of are_same_template
that discard the template argument types:
template <template<class...> class T, class T1, class T2>
struct are_same_template<T<T1>, T<T2>>
即使 T1
和 T2
不同(模板参数类型), are_same_template
是真实类型:
Even if T1
and T2
differ (the template argument types), are_same_template
is a true type:
are_same_template<T<T1>, T<T2>> : std::true_type
关于 template< class ...>
而不是 template< class>
:这是为了容纳事实,而不是 std ::
容器具有隐式模板参数。感谢ConstantinosGlynos使我意识到这一点。
About template<class...>
instead of template<class>
: this is to accomodate the fact than std::
containers have implicit template arguments. Thanks to ConstantinosGlynos for making me aware of it.
这篇关于检查两种类型是否属于同一模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!