如何使用模板来专门化模板?

时间:2018-11-21 16:08:00

标签: c++ c++11 templates

考虑模板类

template<class T>
class Foo
{
};

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

template<>
class Foo<int>
{
};

我遇到一种情况,我想使用模板类来专门化Foo,具体来说是使用bool作为编译时标志:

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

}

用途包括Foo <1,true>和Foo <1,false>。

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

我编码为C ++ 11标准。

3 个答案:

答案 0 :(得分:5)

您需要将主模板更改为

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>
{
};
...

答案 1 :(得分:4)

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

示例:

chrome.windows.onFocusChanged.addListener(windowId => {
  // do something
}, {windowTypes: ['normal']});

而且您可以使用它

template<class T>
class Foo;

template<int, bool> class tag;

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

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

答案 2 :(得分:1)

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

template<class T, bool flag = false>
class Foo
{
};

template<>
class Foo<int>
{
    //"false" specialization (default)
};

template<>
class Foo<int, true>
{
    //"true" specialization
};
相关问题