Har*_*rry 2 c++ type-traits c++11 is-same
如何检查两个类模板实例化是否属于同一个类模板。这是我的代码
#include <iostream>
#include <type_traits>
template<typename T1, typename T2>
class A {
float val;
public:
};
int main() {
A<double, double> a_float_type;
A<int, int> a_int_type;
// how to check whether both a_double_type and a_int_type were instantiated from the same template class A<,>
std::cout << std::is_same<decltype(a_float_type), decltype(a_int_type)>::value << std::endl; // returns false
}
Run Code Online (Sandbox Code Playgroud)
我的编译器只支持C++11
这出奇的简单:
template<typename T1, typename T2>
struct form_same_template : std::false_type
{};
template<template<typename...> class C, typename ... TAs, typename ...TBs>
struct form_same_template<C<TAs...>, C<TBs...>> : std::true_type
{};
#if __cplusplus > 201103L
template<typename T1, typename T2>
constexpr bool form_same_template_v = form_same_template<T1, T2>::value;
#endif
Run Code Online (Sandbox Code Playgroud)
https://godbolt.org/z/hq65PKqKr
如您所见,它通过了基本测试。
如果您希望处理没有类型模板参数的模板,则需要进行一些调整(它失败std::array- 我已经为其添加了测试)。