用于派生特定类型的函数模板专门化

发布于 2024-12-10 19:02:59 字数 261 浏览 3 评论 0原文

class base
{
};

class derived
{
};

template<class T> void foo() {}


int main()
{
    foo<int>();
    foo<derived>();
}

我想将 foo 专门用于 T = base 的推导。这是可能的还是我需要专门针对 base 本身?

class base
{
};

class derived
{
};

template<class T> void foo() {}


int main()
{
    foo<int>();
    foo<derived>();
}

I want to specialize foo for T = derivation of base. Is this possible or do I need to specialize for base itself?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

戒ㄋ 2024-12-17 19:02:59

您可以结合使用 boost::enable_if 和 boost::is_base_of,如文档所述 在 boost::enable_if 手册中

template <class T>
T foo(typename enable_if<boost::is_base_of<base,T> >::type* dummy = 0); 

You can combine boost::enable_if and boost::is_base_of, as is documented in the manual for boost::enable_if.

template <class T>
T foo(typename enable_if<boost::is_base_of<base,T> >::type* dummy = 0); 
梦萦几度 2024-12-17 19:02:59

一种选择是使用 boost类型特征(或者如果感觉勇敢,请查看该库的源代码)。

在编译时,您可以检测一个类型是否从另一个类型继承,从而选择适当的实现。

One option would be to use boost type traits (or if feeling brave, look at the source of that library).

At compile time you can detect if a type inherits from another type and so choose an appropriate implementation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文