【问题标题】:Check if class is of template specialization (with template arguments like bool or int)检查类是否属于模板特化(使用 bool 或 int 等模板参数)
【发布时间】:2019-12-21 16:27:04
【问题描述】:

根据How to tell if template type is an instance of a template class? 和Check if class is a template specialization? 的回答,我创建了以下变体来检查MyClass1、MyClass2 或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;
}

但是,b3 的代码无法编译并给出以下错误:

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

这似乎是因为来自MyClass3 的bool 参数不是class,因此无法通过template &lt;class...&gt; class Template 捕获。

有没有办法解决这个问题,使其适用于任何模板参数列表(不仅仅是class,还包括bool、int 等)?

【问题讨论】:

  • 如果不将is_instance_of_v设为宏(因此模板不需要作为模板模板参数传递),我认为目前是不可能的。
  • 没有通用的模板来处理类型参数和非类型参数。
  • 没有,据我所知。 C++17 为通用模板值引入了auto。你需要像auto 这样更强大的东西:可以拦截通用模板参数的东西:类型、值或模板模板。不幸的是,在 C++ 语言中没有这样的 super-auto
  • 这能回答你的问题吗? Unify type and non-type template parameters
  • 我不得不倾向于同意其他人所说的,即没有可能的实施;但您可能想看看 lambdas 是否可以帮助您。我不会屏住呼吸,但可能值得尝试或研究一下。也许在带有概念的 C++20 中,可能有一种解决方法。

标签: c++ templates c++17 variadic-templates typetraits


【解决方案1】:

没有通用的模板来处理类型参数和非类型参数(和模板模板参数)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-10
    • 2021-09-04
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    相关资源
    最近更新 更多