C++ 中的特殊情况模板

发布于 2024-12-28 18:23:29 字数 550 浏览 6 评论 0 原文

我目前必须优化另一位程序员的代码。他给我留下了很多模板类,我想利用英特尔 IPP-Library 中的函数来加速计算。问题是,大多数时候这些函数要求您知道您正在使用什么数据类型。所以我想重写模板,以便在可以优化操作的情况下它将使用专门的代码。如果不能,它应该回退到原始代码。

问题是我需要检查是否正在使用某种数据类型,但我不知道该怎么做。

一个例子。我想做这样的事情:

 template < class Elem > class Array1D
 {
    Array1D<Elem>& operator += (const Elem& a)
    {
    if (typeof(Elem) == uchar)
    {
       // use special IPP operation here
    }
    else
    {
           // fall back to default behaviour
    }
 }

关于如何做到这一点有什么想法吗?最好没有其他图书馆的帮助。

谢谢

I currently have to optimize code from another programmer. He left me with a lot of template classes and I would like to make use of functions from Intels IPP-Library to speed up computation. The problem is, that most of the time these functions require that you know what datatypes you are using. So I would like to rewrite the template so that in case the operation can be optimized it will use the specialized code. In case it can't it should fall back to the original code.

The problem is that I would need to check if a certain datatype is being used and I don't know how to do that.

An example. I would like to do something like this:

 template < class Elem > class Array1D
 {
    Array1D<Elem>& operator += (const Elem& a)
    {
    if (typeof(Elem) == uchar)
    {
       // use special IPP operation here
    }
    else
    {
           // fall back to default behaviour
    }
 }

Any ideas on how to do this? Preferrably without the help of other libraries.

Thank you

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

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

发布评论

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

评论(4

无声无音无过去 2025-01-04 18:23:30

使用专门化:

    template<> 
    class Array1D<uchar>
    {
        Array1D<uchar>& operator += (const uchar& a)
        {
        // special behaviour
        }
    };

但如果您不想重写 Array1D 中的所有其他函数,请考虑使用运算符 += 的重载。

Use specialization:

    template<> 
    class Array1D<uchar>
    {
        Array1D<uchar>& operator += (const uchar& a)
        {
        // special behaviour
        }
    };

But if you dont want to rewrite all other functions in Array1D consider using overloading for operator+=.

青衫负雪 2025-01-04 18:23:30

专门化模板,例如:

template<> class Array1D<char>
 {
    Array1D<char>& operator += (const char& a)
    {
       // use special IPP operation here
    }
 }

并且在通用版本中使用默认行为。

Specialize template like:

template<> class Array1D<char>
 {
    Array1D<char>& operator += (const char& a)
    {
       // use special IPP operation here
    }
 }

and in general version use default behavior.

旧人九事 2025-01-04 18:23:30

我认为你想要模板专业化。 本文介绍了基础知识。

I think you want template specialization. This article explains the basics.

漆黑的白昼 2025-01-04 18:23:29

在我看来,您的用例是模板专业化<的完美场景/强>。

It seems to me that Your use case is an perfect scenario for Template Specialization.

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