如何在 C++ 中的模板化类中为单个方法创建特化?

编程入门 行业动态 更新时间:2024-10-13 06:16:48
本文介绍了如何在 C++ 中的模板化类中为单个方法创建特化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

已经提出了许多问题,它们与我将在这里提出的问题相似,但我认为它们并不相同.

Many questions have been asked and they are similar to the one I am going to ask here, but they are not the same I think.

我有一个模板类:

namespace app {
template <typename T>
class MyCLass {
public:
  void dosome();
  void doother();
}
} /*ns*/

和实现:

template <typename T>
app::MyClass<T>::dosome() {}
template <typename T>
app::MyClass<T>::doother() {}

当我有一个该类的实例时,将 char 作为模板参数提供给它,我希望函数 dosome() 以完全不同的方式运行.但我只是希望该函数的行为有所不同,其他一切都必须保持不变.

When I have an instance of that class to which a char is provided as template parameter, I want function dosome() to behave in a totally different way. But I just want that function to behave differently, everything else must still act the same.

我尝试输入:

template<>
app::MyCLass<char>::dosome() {
}

但是编译器告诉我我正在尝试在不同的命名空间中创建一个专业化.

But the compiler tells me that I am trying to create a specialization in a different namespace.

所以当我有这样的代码时:

So when I have a code like this:

app::MyCLass<int> a;
app::MyCLass<char> b;
a.dosome(); // This must call the generic template definition
b.dosome(); // This must call the specialization
a.doother(); // This must call the generic template definition
b.doother(); // This must call the generic template definition

在其他问题中,我看到人们为整个班级创造了完全不同的专业.但我只想要一种方法的特化.

In other questions I saw people creating totally different specialization of the entire class. But I only want a specialization of a single method.

推荐答案

你可以为所欲为:http://ideone/oKTFPC

//标题

namespace My
{

template <typename T>
class MyClass {
public:
    void dosome();
    void doother();
};

template <typename T> void MyClass<T>::dosome() {}
template <typename T> void MyClass<T>::doother() {}

template<> void MyClass<char>::dosome();

}

//cpp 或在标题中

// cpp or in header

template<>
void My::MyClass<char>::dosome() {
    std::cout << "specialization" << std::endl;
}

或使用替代符号

namespace My {
template<>
void MyClass<char>::dosome() {
    std::cout << "specialization" << std::endl;
}
}

这篇关于如何在 C++ 中的模板化类中为单个方法创建特化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 06:17:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405449.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:特化   类中   模板   方法   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!