【发布时间】:2014-09-10 23:00:03
【问题描述】:
我正在尝试编写一个类似于std::to_string 的模板函数,它适用于基本类型以及 STL 容器的迭代器。但我不确定如何编写足够具体的模板来识别迭代器。
到目前为止,我尝试的是尝试在 STL 容器中使用 iterator typedef
template<typename... Args, template <typename...> class Container>
static string to_string(typename Container<Args...>::iterator s) { ...
下面附上了一个最小的例子。代码编译成功,但模板函数My::to_string 无法匹配上述签名,并将std::set<int>::iterator 视为默认类型。
我的问题是如何以通用方式正确编写此代码,以便模板函数 My::to_string 可以拾取迭代器,但不要将迭代器与其他标准模板类型(如 std::string)混淆。
提前致谢。
#include <set>
#include <iostream>
using namespace std;
class My{
//base case
template<typename T>
static string to_string(const T& t) {
return "basic ";
}
//specialization for string
template <typename Char, typename Traits, typename Alloc>
static string to_string(const std::basic_string<Char, Traits, Alloc>& s) {
return (string)s;
}
//Problem line: how to write specialization for iterators of standard containers?
template<typename... Args, template <typename...> class Container>
static string to_string(typename Container<Args...>::iterator s) {
return "itor ";
}
};
int main() {
int i = 2;
string str = "Hello";
set<int> s;
s.insert(i);
cout << to_string(i) << ", " << str << ", "
<< to_string(s.begin()) << endl; //didn't get captured by iterator spec.
}
输出:
basic, Hello, basic
期望的输出:
basic, Hello, itor
【问题讨论】:
-
::的左边是非推断上下文。这也可能通常是不可能的。如果两个容器都使用原始指针作为迭代器怎么办?
标签: c++ templates c++11 stl iterator