【问题标题】:How can I specialise a template with a template?如何使用模板专门化模板?
【发布时间】:2018-11-21 16:08:00
【问题描述】:

考虑一个模板类

template<class T>
class Foo
{
};

我可以为此编写一个简单的专业化

template<>
class Foo<int>
{
};

我有一种情况,我想用一个模板类专门化 Foo,详细地用一个用作编译时标志的 bool:

template<>
class Foo<int, bool> // Clearly not the correct notation.
{

}

用途包括 Foo 和 Foo。

类名的正确表示法是什么,我在其中标记了“显然不是正确的表示法。”?

我按照 C++11 标准编写代码。

【问题讨论】:

  • Foo&lt;T&gt; 和 Foo&lt;T, E&gt; 是不同的模板。
  • 我不清楚你所说的“我想用一个模板类来专门化 Foo”是什么意思,但你可能想要专门化一种编码这两种类型的类型,比如 Foo&lt;std::tuple&lt;int, bool&gt;&gt;。

标签: c++ c++11 templates


【解决方案1】:

您需要将主模板更改为

template<class T, bool B>
class Foo
{
};

然后你可以像这样专门化它

template<>
class Foo<int, true>
{
};

template<>
class Foo<int, false>
{
};
...

然后你会像这样使用它

Foo<int, true> FooT;
Foo<int, false> FooF;

如果您要为第一个参数使用值,例如

Foo<1, true>

那么主模板应该是

template<int I, bool B>
class Foo
{
};

然后你可以像这样专门化它

template<>
class Foo<1, true>
{
};

template<>
class Foo<1, false>
{
};
...

【讨论】:

  • 谢谢。我想我会这样做。
  • @SasidiranSangamanautram 我刚刚在你的 Q 中注意到你想使用 Foo 就像 Foo&lt;1, true&gt;。这真的是你想要使用的Foo吗?
  • 几乎是的,第一个参数实际上是一个枚举,但我将它简化为一个 int。
  • @SasidiranSangamanautram 好的。我已经在答案中添加了如何得到它,因为我最初提出的不同。
【解决方案2】:

这是不可能的。您的模板需要一个参数,您不能专门针对两个参数。但是,您可以(部分)将它专门用于其他一些类型,它是两个参数的模板。

例子:

template<class T>
class Foo;

template<int, bool> class tag;

template<int>
class Foo<tag<int, true>> { ... };

template<int>
class Foo<tag<int, false>> { ... };

而且你可以使用它

Foo<tag<1, true>> foo;

【讨论】:

    【解决方案3】:

    看起来像模板参数的默认值。

    template<class T, bool flag = false>
    class Foo
    {
    };
    
    template<>
    class Foo<int>
    {
        //"false" specialization (default)
    };
    
    template<>
    class Foo<int, true>
    {
        //"true" specialization
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多