【问题标题】:C++ Partial Template Specialization and NatvisC++ 部分模板专业化和 Natvis
【发布时间】:2019-10-20 20:49:46
【问题描述】:

我正在尝试为部分专业化类型创建 Visual Studio 调试可视化工具。例如,假设我有这样的事情:

template <typename T>
struct Foo
{
    T bar;
};

template <typename T>
struct Foo<T*>
{
    T baz;
};

没有部分特化,这很容易:

<Type Name="Foo&lt;*&gt;"> ... </Type>

有了完全的专业化,这也很容易:

<Type Name="Foo&lt;int&gt;"> ... </Type>

但是我如何涵盖部分专业化?这甚至被支持吗?如果没有,是否有解决方法?

【问题讨论】:

    标签: c++ visual-studio template-specialization natvis


    【解决方案1】:

    简短回答 - 不可以。您不能在 natvis 类型名称 &lt;Type Name="Foo&amp;lt;*&amp;gt;"&gt; 中指定类型限定符、引用等。

    但是:

    您可以将模板的 typename 参数用作字符串并与类型进行比较。比如在节点的Condition属性中:

    <Type Name="Foo&lt;*&gt;">
      <DisplayString Condition="strcmp(&quot;$T1&quot;,&quot;short&quot;)==0">specialization short</DisplayString>
      <DisplayString Condition="strcmp(&quot;$T1&quot;,&quot;int &amp;&quot;)==0">specialization int &amp;</DisplayString>
      <DisplayString>unspecified specialization</DisplayString>
    </Type>
    

    对于 Foo&lt;short&gt;,您将看到 specialization short 和 unspecified specialization 对于其他。

    例子:

    template <typename T, typename U>
    struct Foo
    {
        T bar;
    };
    
    template <typename U>
    struct Foo<int &, U>
    {
        U baz;
    };
    int main()
    {
        int gg = 0;
        Foo<short, int> a;
        Foo<int, int> b;
        Foo<int &, int> c;
    

    纳特维斯:

    <Type Name="Foo&lt;*,*&gt;" >
      <DisplayString Condition="strcmp(&quot;$T1&quot;,&quot;short&quot;)==0">specialization short</DisplayString>
      <DisplayString>unspecified specialization</DisplayString>
    </Type>
    
    <Type Name="Foo&lt;int&amp;,*&gt;">
      <DisplayString>partial specialization int&amp;</DisplayString>
    </Type>
    

    结果:

    或者你,如果你的部分专业类型中有一些独特的成员,可以使用Priority 选项。

    例子:

    template <typename T>
    struct Foo
    {
        T bar;
    };
    
    template <typename U>
    struct Foo<U &>
    {
        U baz;
    };
    int main()
    {
        int g = 0;
        Foo<short> a;
        Foo<int> b;
        Foo<int &> c{g};
    

    纳特维斯:

    <Type Name="Foo&lt;*&gt;">
      <DisplayString>partial specialization {baz}</DisplayString>
    </Type>
    
    <Type Name="Foo&lt;*&gt;" Priority="Low">
      <DisplayString>other specialization</DisplayString>
    </Type>
    

    结果:

    【讨论】:

    • Foo&lt;short&gt; 是一个完整的专业化。这个语法对template &lt;typename T&gt; Foo&lt;T&amp;&gt; 有什么作用?
    • 感谢您的帮助澄清! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    相关资源
    最近更新 更多