从同一类的专用模板的静态函数访问类模板成员
我仍在学习 C++ 模板,并且遇到了有关使用以下内容从专用静态函数调用成员的问题。 GCC 抱怨:“静态成员函数中成员 C
template <typename T = const char*>
class C { };
//specialization for const char*
template <>
class C <const char*> {
public:
C() { }
static void echo(int x);
private:
int value;
};
//error occurs here
void C<const char*>::echo(int x) {
value = x;
}
非常感谢您提供的任何见解。
I am still learning C++ templates, and have encountered a problem regarding calling members from specialized static functions using the following. GCC complains: "invalid use of member C< const char* >::value in static member function." I have searched this forum and a few others, and even my friend Google cannot aid me. I figure the error has to be something I am overlooking, as I made a non-specialized version of the class (with the same static member function), and I still get the same error. Any ideas?
template <typename T = const char*>
class C { };
//specialization for const char*
template <>
class C <const char*> {
public:
C() { }
static void echo(int x);
private:
int value;
};
//error occurs here
void C<const char*>::echo(int x) {
value = x;
}
Many thanks to any insight you can offer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它与模板无关。
value
是一个实例成员,只有在提供C
实例时才能访问。静态函数没有this
实例,并且您没有使用.
或->
成员访问运算符来显式提供实例。It has nothing to do with templates.
value
is an instance member, and can only be accessed when you provide an instance ofC
. A static function has nothis
instance, and you haven't used the.
or->
member access operator either to explicitly provide an instance.echo()
是静态的,因此无法访问实例级字段value
。要么使函数成为非静态,要么使字段成为静态。
The
echo()
is static an therefore cannot access the instance-level fieldvalue
.Either make the function non-static or make the field static.