【问题标题】:C++ is possible to make only one method templated?C++ 可以只使一种方法模板化吗?
【发布时间】:2014-07-31 13:15:50
【问题描述】:

我有一个类,我只需要一个模板方法,像这样:

/* A.h */

class A {
public: 
  void foo() const; 
private:
  template <class T> 
  void foo2(const T& t, const std::string& s) {
     /* */
  }
}

这编译得很好,但是如果在 foo 专业化中我尝试调用 foo2 我会得到错误:

/* A.cpp */

void A::foo() {
   this->foo2(1, "test");
}

错误是:

passing ‘const A’ as ‘this’ argument of ‘void A::foo2(const T&, const
string&) [with T = int, std::string = std::basic_string<char>]’
discards qualifiers [-fpermissive]

【问题讨论】:

  • 错误是...?
  • @SteveTownsend "what T to infer from the literal 1" - 好吧,它可以毫无问题地推断出int,因为文字1的类型是int...
  • 没有foo 特化,因为它不是模板。你应该告诉我们错误是什么,我们通常不会在这里练习心灵感应
  • @SteveTownsend 不起作用..
  • 您遇到了 const 正确性问题,并且缺少部分错误消息。 SSCCE,请。

标签: c++ eclipse templates c++03


【解决方案1】:

是的,有可能。

我认为您在示例中错过了 void foo() 的 const 修饰符,不是吗?

如果我的假设是正确的,也为 foo2 加上一个 const 修饰符。

【讨论】:

    【解决方案2】:

    您正在同一个对象上调用来自 const 函数 foo 的非 const 函数 foo2。因此错误。 BTW this 在通话中是没有必要的:

    this->foo2(1, "test");
    

    以下也可以:

    foo2(1, "test");
    

    【讨论】:

      【解决方案3】:

      您在类声明的末尾缺少;,并且您的 const 正确性似乎不一致。这在 vc12 中为我编译:

      /* A.h */
      
      class A {
      public:
          void foo() const;
      private:
          template <class T>
          void foo2(const T& t, const std::string& s) const {
              /* */
          }
      };
      void A::foo() const {
          this->foo2(1, "test");
      }
      

      【讨论】:

        猜你喜欢
        • 2012-02-16
        • 1970-01-01
        • 2014-08-18
        • 1970-01-01
        • 2017-07-01
        • 1970-01-01
        • 2021-10-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多