【问题标题】:C++ Function Template Error with namespace命名空间的 C++ 函数模板错误
【发布时间】:2014-08-11 11:01:59
【问题描述】:

我在编写一个简单的函数模板时遇到错误。如果有人能告诉我我做错了什么,我将不胜感激。

错误:

z:\n4\pkg\mrservers\mrimaging\seq\cestipat_offsetseries\GlobalVariable.h(118) : error C2825: 'type1': must be a class or namespace when followed by '::'
z:\n4\pkg\mrservers\mrimaging\seq\cestipat_offsetseries\GlobalVariable.h(118) : error C2039: 'const_iterator' : is not a member of '`global namespace''
z:\n4\pkg\mrservers\mrimaging\seq\cestipat_offsetseries\GlobalVariable.h(118) : error C2146: syntax error : missing ';' before identifier 'i1'

…… 我的功能如下(我已经标记了错误出现的行号)

template<typename type1>
void PrintVector(type1 VectorIn_1) {    
    long lLenghtVec = VectorIn_1.size();
    typename type1::const_iterator  i1 = VectorIn_1.begin();    // line 118
    for(int i = 0; i != lLenghtVec; ++i){               // line 119
        std::cout << std::setw(4) << *i1 << " " <<std::endl;    
        ++i1;
    }
}

使用的命名空间: 一开始,我使用了ARMADILLOS lib

#include <armadillo>.
#define ARMA_64BIT_WORD
#include "armadillo-3-910-0/include/armadillo"
using namespace arma;

【问题讨论】:

  • 这个函数怎么调用? (那么, type1 的类型是什么?)我怀疑它不是容器类型
  • 表示type1没有const_iterator这样的类型。也许您尝试使用 POD 调用您的函数?
  • 顺便说一句,你可以通过 const 引用来避免无用的副本。

标签: c++ function templates


【解决方案1】:

你没有正确调用你的模板(大概是传递了一个非类型,但是你没有显示调用站点),如下compiles and run fine(我没有修改你的函数):

#include <iostream>
#include <vector>
#include <iomanip>

template<typename type1>
void PrintVector(type1 VectorIn_1) {    
    long lLenghtVec = VectorIn_1.size();
    typename type1::const_iterator  i1 = VectorIn_1.begin();    // line 118
    for(int i = 0; i != lLenghtVec; ++i){               // line 119
        std::cout << std::setw(4) << *i1 << " " <<std::endl;    
        ++i1;
    }
}

int main() {
    std::vector<int> v = { 1, 2, 3, 4};
    PrintVector<std::vector<int>>(v);
}

注意:

  • 您应该更喜欢将迭代器而不是容器传递给您的函数,它使您的代码更加通用(即 ala C++ 标准库)

【讨论】:

猜你喜欢
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 2014-11-14
相关资源
最近更新 更多