问题描述
限时送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:关键词]
发布评论