std :: vector的Typedef和ostream运算符

Rhy*_*den 4 c++ templates typedef vector ostream

我创建了一个类Chromosome,它最终只是一个带有ostream运算符的vector的包装器,所以我决定改为使用typedef vector.但是,我在使用模板化的ostream运算符时遇到了麻烦......这是最好的方法吗?(我已经看到了一些方法并且没有得到任何工作)

template<typename G>
class Chromosome {
 public:
  typedef typename std::vector<G> type;
  typedef typename std::pair<type *,type *> ptr_pair;
};

template<typename G> //line 19 below:
std::ostream& operator<<(std::ostream& os, const Chromosome<G>::type& chromosome) {
  for(auto iter = chromosome.begin(); iter != chromosome.end(); ++iter)
    std::cout << *iter;
  return os;
}
Run Code Online (Sandbox Code Playgroud)

目前我得到的错误是:

chromosome.h:19: error: expected unqualified-id before ‘&’ token
chromosome.h:19: error: expected ‘)’ before ‘&’ token
chromosome.h:19: error: expected initializer before ‘&’ token
Run Code Online (Sandbox Code Playgroud)

干杯.

tem*_*def 6

不幸的是,没有干净的方法来执行此操作,因为编译器无法G从函数声明中推断出类型

template<typename G>
std::ostream& operator<<(std::ostream& os, const typename Chromosome<G>::type& chromosome);
Run Code Online (Sandbox Code Playgroud)

原因是如果你专注Chromosome于不同的类型,你最终可能会遇到编译器无法明确推断的情况G.例如:

template <typename G> class Chromosome {
public:
    typedef std::vector<G> type; // No typename needed here, BTW
};

template <> class Chromosome<int> {
public:
    typedef std::vector<double> type;
};
Run Code Online (Sandbox Code Playgroud)

现在,如果你这样做会发生什么?

vector<double> v;
cout << v << endl;
Run Code Online (Sandbox Code Playgroud)

编译器无法分辨Gdoubleint在这种情况下,因为两者Chromosome<int>Chromosome<double>具有vector<double>作为其嵌套类型.

要解决此问题,您必须明确使用该类型vector<G>作为参数:

template<typename G>
std::ostream& operator<<(std::ostream& os, const std::vector<G>& chromosome);
Run Code Online (Sandbox Code Playgroud)

不幸的是,实际上并没有更好的方法.这并不是语言中的缺陷,因为有充分的理由禁止它,但实际上它确实阻止你在这种情况下做你想做的事情.

  • 谢谢,我明白这是如何运作的.使用vector完全没问题,因为我只是尝试使用Chromosome <G> :: type来提高可读性.你能解释一下"这里不需要打字吗"吗? (2认同)