【问题标题】:Templated function can't be found, despite being declared尽管已声明,但找不到模板化函数
【发布时间】: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 它应该选择后者,因为它更专业。

谢谢!

【问题讨论】:

标签: c++ templates


【解决方案1】:

好吧,正如我们所知,你必须在 C++ 中使用它之前声明函数,你声明了

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) 函数中使用它。

您在这里错过的是您在使用std::pair 的版本之后声明了std::vector 版本,因此它没有找到要使用的正确函数模板。

要解决此问题,请将std::vector 版本移至std::pair 版本之前或转发声明。

【讨论】:

  • "我们知道,你必须在 C++ 中使用它之前声明该函数" 我不知道。 toJson 不是从属名称吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-27
  • 2022-11-03
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多