check class template instantiations belong to same class template

96 views Asked by At

How to check if two class template instantiations belong to same class template. This is my code

#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
}

My compiler only supports C++11

1

There are 1 answers

4
Marek R On

This is surprisingly quite simple:

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

https://godbolt.org/z/hq65PKqKr

As you can see it passes basic tests.

Some tweaks are needed if you wish to handle templates with none type template parameters (it fails on std::array - I've added test for it).