【发布时间】:2011-09-30 22:35:57
【问题描述】:
我这里有一个代码示例:http://codepad.org/9JhV7Fuu
使用此代码:
#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <set>
namespace Json {
template <typename ValueType>
struct Value {
Value() {}
Value(int) {}
Value(float) {}
Value(unsigned int) {}
Value(std::string) {}
};
}
template <typename T>
Json::Value<T> toJson(T x) {
return Json::Value<T>(x);
}
template <typename T, typename U>
Json::Value< std::pair<T, U> > toJson(std::pair<T, U> const& rh) {
Json::Value< std::pair<T, U> > return_value;
toJson(rh.first);
toJson(rh.second);
return return_value;
}
template <typename T>
Json::Value<T> toJsonContainer(T const& rh) {
Json::Value<T> return_value;
for (typename T::const_iterator it = rh.begin(); it != rh.end(); ++it) {
toJson(*it);
}
return return_value;
}
template <typename T, typename U>
Json::Value< std::map<T, U> > toJson(std::map<T, U> const& rh) {
return toJsonContainer(rh);
}
template <typename T>
Json::Value< std::vector<T> > toJson(std::vector<T> const& rh) {
return toJsonContainer(rh);
}
int main(int argc, char **argv) {
std::map<std::string, std::vector<unsigned int>> x;
toJson(x);
return 0;
}
我收到此错误:
main.cpp: In function ‘Json::Value<T> toJson(T) [with T = std::vector<unsigned int>]’:
main.cpp:27:2: instantiated from ‘Json::Value<std::pair<_T1, _T2> > toJson(const std::pair<_T1, _T2>&) [with T = const std::basic_string<char>, U = std::vector<unsigned int>]’
main.cpp:36:3: instantiated from ‘Json::Value<T> toJsonContainer(const T&) [with T = std::map<std::basic_string<char>, std::vector<unsigned int> >]’
main.cpp:44:27: instantiated from ‘Json::Value<std::map<T, U> > toJson(const std::map<T, U>&) [with T = std::basic_string<char>, U = std::vector<unsigned int>]’
main.cpp:54:10: instantiated from here
main.cpp:20:25: error: no matching function for call to ‘Json::Value<std::vector<unsigned int> >::Value(std::vector<unsigned int>&)’
请注意,问题是编译器选择的原因
template <typename T> Json::Value<T> toJson(T x);
结束
template <typename T> Json::Value< std::vector<T> > toJson(std::vector<T> const& rh);
Afaik 它应该选择后者,因为它更专业。
谢谢!
【问题讨论】:
-
您没有在 Value 中定义接受 std::vector
&. 的构造函数 -
你的 Value 结构不能只有一个通过引用获取类型 T 的构造函数吗?
-
toJson(rh.first);这不可能。