C++编程思想 第2卷 第5章 深入理解模板 模板参数 以template关键字作为提示

当一个类型标识符不是预期的标识符时
正好typename关键字可以帮助编译器识别它们
但编译器却还存在一些潜在的困难
比如 < 字符 和 > 字符

//: C05:DotTemplate.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Illustrate the .template construct.
#include <bitset>
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;

template<class charT, size_t N>
basic_string<charT> bitsetToString(const bitset<N>& bs) {
  return bs. template to_string<charT, char_traits<charT>,
                                allocator<charT> >();
}

int main() {
  bitset<10> bs;
  bs.set(1);
  bs.set(5);
  cout << bs << endl; // 0000100010
  string s = bitsetToString<char>(bs);
  cout << s << endl;  // 0000100010
  getchar();
} ///:~


输出
0000100010
0000100010

类bitset通过它的to_string成员函数支持向字符串对象的转换
为了支持向多种字符串类的转换
to_string本身就做成了一个模板

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/82083435