检查两种类型是否属于同一模板

use*_*019 8 c++ sfinae type-traits

我想检查两种类型是否属于同一模板。作为示例,我希望返回以下代码片段true,因为尽管内部元素具有不同类型,但两个对象都是向量。

在编译时进行检查很重要(这就是该函数为 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);
}
Run Code Online (Sandbox Code Playgroud)

YSC*_*YSC 5

干得好:

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;
}
Run Code Online (Sandbox Code Playgroud)

演示:http://coliru.stacked-crooked.com/a/8533c694968f4dbb


are_same_template这是通过提供丢弃模板参数类型的专门化来实现的:

template <template<class...> class T, class T1, class T2>
struct are_same_template<T<T1>, T<T2>>
Run Code Online (Sandbox Code Playgroud)

即使 和T1不同T2(模板参数类型),are_same_template也是一个真实类型:

are_same_template<T<T1>, T<T2>> : std::true_type
Run Code Online (Sandbox Code Playgroud)

关于template<class...>而不是template<class>:这是为了适应容器具有隐式模板参数的事实std::。感谢 ConstantinosGlynos 让我意识到这一点。