Prev: why don't the STL containers all inherit from a common container class to allow generic iteration?
Next: concurrent linked queue class for C++?
From: Georg Sauthoff on 8 Dec 2009 08:54 Hi, consider this code: #include <iostream> template<typename T> inline int match(const T &x) { return 23; } template <typename T> inline int not_match(const T &x) { return match(x) + 1; } template <> inline int match<int>(const int &x) { return 42; } inline int match(const double &d) { return 62; } int main() { int i = 0; double d = 0; std::cout << not_match(i) << ' ' << not_match(d) << '\n'; return 0; } I would expect the output: 43 63 with g++ 4.4.1 it prints: 43 24 with Sun CC 5.10 it prints: 43 63 Thus, the question, who is right? I.e. who is standard conforming? Does a compiler has to consider only specialized versions or overloaded functions, too - in the case of the lookup of a dependent function name? Best regards Georg -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: 萌 朱 on 11 Dec 2009 05:19
On Dec 8, 8:54 pm, Georg Sauthoff <g_sauth...(a)web.de> wrote: > Hi, > > consider this code: > > #include <iostream> > > template<typename T> inline int match(const T &x) > { > return 23; > > } > > template <typename T> inline int not_match(const T &x) > { > return match(x) + 1; > > } > > template <> inline int match<int>(const int &x) > { > return 42; > > } > > inline int match(const double &d) > { > return 62; > > } > > int main() > { > int i = 0; > double d = 0; > std::cout << not_match(i) << ' ' << not_match(d) << '\n'; > return 0; > > } > > I would expect the output: > 43 63 > > with g++ 4.4.1 it prints: > 43 24 > > with Sun CC 5.10 it prints: > 43 63 > > Thus, the question, who is right? I.e. who is standard conforming? I think g++ is correct because by the time the compiler sees not_match it only saw one version of match and that is the general template match. So that is the only choice. However, if you move your definition of match(cost double&) before the not_match definition. The compiler will notice that one and correctly resolves that ordinary function is better matched in your second call. In this case, g++ also outputs 43 63. So I think g++ is correct in both situation. > > Does a compiler has to consider only specialized versions or > overloaded > functions, too - in the case of the lookup of a dependent function > name? -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |