6

Based on the answers from How to tell if template type is an instance of a template class? and Check if class is a template specialization? I created the following variant to check for specific instantiations of MyClass1, MyClass2 or MyClass3:

template <class T, template <class...> class Template>
constexpr bool is_instance_of_v = false;

template <template <class...> class Template, class... Args>
constexpr bool is_instance_of_v<Template<Args...>, Template> = true;

template<class T> struct MyClass1 { };
template<class T, class B> struct MyClass2 { };
template<class T, bool B> struct MyClass3 { };


int main(int argc, char* argv[])
{
    constexpr bool b1 = is_instance_of_v<MyClass1<float>, MyClass1>;
    constexpr bool b2 = is_instance_of_v<MyClass1<float>, MyClass2>;
    // constexpr bool b3 = is_instance_of_v<MyClass1<float>, MyClass3>;  // <-- does not compile

    return 0;
}

However, the code for b3 does not compile & gives the following error:

error C3201: the template parameter list for class template 'MyClass3' does not match the 
                 template parameter list for template parameter 'Template'
error C2062: type 'unknown-type' unexpected

It seems this is because the bool argument from MyClass3 is not a class, and thus cannot be captured via template <class...> class Template.

Is there a way to fix this so that it works for any list of template arguments (not just class, but also bool, int, etc.)?

Phil-ZXX
  • 2,359
  • 2
  • 28
  • 40
  • Without making `is_instance_of_v` a macro (so the template does not need to be passed as template template parameter), I don't think that is currently possible. – walnut Dec 21 '19 at 16:51
  • There are no common templates to handle type parameters and non type parameters. – Jarod42 Dec 21 '19 at 16:56
  • No, as far I know. C++17 introduced `auto` for a generic template value. You needs something as `auto` but more powerful: something that can intercept a generic template parameter: type, value or template-template. Unfortunately, there isn't, in C++ language, such super-`auto` – max66 Dec 21 '19 at 16:56
  • Does this answer your question? [Unify type and non-type template parameters](https://stackoverflow.com/questions/29342064/unify-type-and-non-type-template-parameters) – Davis Herring Dec 21 '19 at 20:33
  • I have to tend to agree with what others have said, that there is no possible implementation; but you might want to see if lambdas could possibly help you here. I wouldn't hold your breath but it might be worth trying or looking into it. Maybe in C++20 with concepts, there might be a workaround. – Francis Cugler Dec 23 '19 at 03:31

1 Answers1

3

There are no common templates to handle type parameters and non type parameters (and template template parameters).

Jarod42
  • 203,559
  • 14
  • 181
  • 302