【问题标题】:Accessing class template members from static functions of a specialized template of the same class从同一类的专用模板的静态函数访问类模板成员
【发布时间】:2011-10-31 07:14:25
【问题描述】:

我仍在学习 C++ 模板,并且遇到了关于使用以下方法从专门的静态函数调用成员的问题。 GCC 抱怨:“在静态成员函数中无效使用成员 C::value。” 我已经搜索了这个论坛和其他一些论坛,甚至我的朋友 Google 也无法帮助我。我认为错误必须是我忽略的东西,因为我制作了该类的非专业版本(具有相同的静态成员函数),但我仍然得到相同的错误。有什么想法吗?

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;
}

非常感谢您提供的任何见解。

【问题讨论】:

    标签: c++ static-members


    【解决方案1】:

    与模板无关。

    value 是实例成员,只有在提供C 的实例时才能访问。静态函数没有 this 实例,您也没有使用 .-&gt; 成员访问运算符来显式提供实例。

    【讨论】:

    • 感谢@Ben,正是我想要的!很好的解释。 +1
    【解决方案2】:

    echo() 是静态的,因此无法访问实例级字段 value

    要么将函数设为非静态,要么将字段设为静态。

    【讨论】:

    • 更准确地说,它不能使用非限定名称访问实例成员。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 2017-10-20
    • 2010-12-22
    相关资源
    最近更新 更多