成员模板

时间:2016-03-30 11:15:42

标签: c++ templates pc-lint

我目前正在使用PC-Lint(版本9.00j和l),这给了我一些代码的错误和警告。代码编译良好并按预期运行。以下是它的简化版本:

#include <iostream>
#include <vector>

typedef unsigned char uint8_t;

class Test
{
  uint8_t          inputList[10];
  std::vector<int> resultList;

public:

  Test() : resultList()
  {
    for (uint8_t ii = 0; ii < 10; ++ii) 
      inputList[ii] = ii;
  }

  template<int list_size, typename ResultListType>
  void loadList(const uint8_t (& inputList)[list_size],
                ResultListType & resultList) const
  {
    for (uint8_t ii = 0; ii < list_size; ++ii) 
      resultList.push_back(inputList[ii]);
  }

  void run()
  {
    loadList(inputList, resultList);
  }

  void print()
  {
    std::vector<int>::iterator it;
    for (it = resultList.begin(); it != resultList.end(); ++it)
      std::cout << *it << std::endl;
  }
};

int main()
{
  Test t;
  t.run();
  t.print();
}

在Gimpel的在线演示中运行时,我收到了这些错误和警告:

    30      loadList(inputList, resultList);
diy.cpp  30  Error 1025:  No template matches invocation 'Test::loadList(unsigned char [10], std::vector<int>)', 1 candidates found, 1 matched the argument count
diy.cpp  30  Info 1703:  Function 'Test::loadList(const unsigned char (&)[V], <2>&) const' arbitrarily selected. Refer to Error 1025
diy.cpp  30  Error 1032:  Member 'loadList' cannot be called without object
diy.cpp  30  Error 1058:  While calling 'Test::loadList(const unsigned char (&)[V], <2>&) const': Initializing a non-const reference '<2>&' with a non-lvalue (a temporary object of type 'std::vector<int>')
diy.cpp  30  Warning 1514:  Creating temporary to copy 'std::vector<int>' to '<2>&' (context: arg. no. 2)

所以基本上,PC-Lint试图告诉我它只会偶然找到正确的模板参数,并且只会填充矢量的临时副本。但代码运行良好,resultList包含数据!

谁能告诉我这里发生了什么? PC-Lint是对的还是出了什么问题,或者这只是PC-Lint的错误?

1 个答案:

答案 0 :(得分:0)

问题是loadList被标记为const,但您将非常量引用传递给您修改的成员变量resultList

loadList函数确实不会直接修改this实例 ,但由于您仍然修改了成员变量,因此该函数不能是常量。

创建传递给函数的临时向量,或者使函数不是const