gpt4 book ai didi

c++ - 如何使用模板专门化模板?

转载 作者:太空宇宙 更新时间:2023-11-04 14:47:02 24 4
gpt4 key购买 nike

考虑一个模板类

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 标准编写代码。

最佳答案

您需要将主模板更改为

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

关于c++ - 如何使用模板专门化模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53416106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com