带有一个专门用于 C++ 的方法的模板类

编程入门 行业动态 更新时间:2024-10-09 01:18:26
本文介绍了带有一个专门用于 C++ 的方法的模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我只有一个用 C++ 编写的学校作业的 hpp 文件(我不允许添加 cpp 文件,声明和实现都应该写在文件中).

I only have an hpp file for a school assignment in C++ (I am not allowed to add a cpp file, declaration and implementation should be both written in the file).

我在里面写了这段代码:

I wrote this code inside it:

template<class T>
class Matrix
{
   void foo()
   {
       //do something for a T variable.
   }
};

我想添加另一个 foo 方法,但是这个 foo() 将专门用于一个 .我在某些地方读到过,我需要声明一个新的专业化类才能使其工作.但我想要的是专门的 foo 将位于原始 foo 的正下方,所以它看起来像这样:

I would like to add another foo method, but this foo() will be specialized for only an <int>. I have read in some places that I need to declare a new specialization class for this to work. But what I want is that the specialized foo will lie just beneath the original foo, so it will look like this:

template<class T>
class Matrix
{
   void foo(T x)
   {
       //do something for a T variable.
   }
   template<> void foo<int>(int x)
   {
       //do something for an int variable.
   }
};

为什么我收到此语法的错误('<' 标记之前的预期未限定 ID")?为什么这不可能?如何在不声明新的专用类的情况下解决此问题?

谢谢

推荐答案

foo 不是模板.它是模板的成员函数.因此 foo 是没有意义的.(此外,必须在命名空间范围内声明显式特化.)

foo isn't a template. It's a member function of a template. Thus foo<int> is meaningless. (Also, explicit specializations must be declared at namespace scope.)

您可以显式特化类模板的特定隐式实例化的成员函数:

You can explicitly specialize a member function of a particular implicit instantiation of a class template:

template<class T>
class Matrix
{
   void foo(T x)
   {
       //do something for a T variable.
   }
};

// must mark this inline to avoid ODR violations
// when it's defined in a header
template<> inline void Matrix<int>::foo(int x)
{
     //do something for an int variable.
}

这篇关于带有一个专门用于 C++ 的方法的模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

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

发布评论

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

>www.elefans.com

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