der folgende Code Gegeben:Probleme mit Überladungsauflösung und Operator << für Templat-Typen - Teil 2
#include <string>
#include <type_traits>
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
namespace has_insertion_operator_impl {
typedef char no;
typedef char yes[2];
struct any_t {
template <typename T>
any_t(T const&);
};
no operator<<(ostream const&, any_t const&);
yes& test(ostream&);
no test(no);
template <typename T>
struct has_insertion_operator {
static ostream& s;
static T const& t;
static bool const value = sizeof(test(s << t)) == sizeof(yes);
};
}
template <typename T>
struct has_insertion_operator : has_insertion_operator_impl::has_insertion_operator<T> {};
template <class T>
typename enable_if<has_insertion_operator<T>::value, string>::type stringify(const T& in) {
stringstream stream;
stream << in;
return stream.str();
}
template <class T>
typename enable_if< ! has_insertion_operator<T>::value, string>::type stringify(const T&) {
return "{?}";
}
// ======= OVERLOADS PROVIDED BY THE USER =======
template<typename T, typename T2>
struct myType { T data; T2 op; };
template<typename T, typename T2>
ostream& operator<<(ostream& s, const myType<T, T2>&) { s << "myType"; return s; }
template<typename T>
ostream& operator<<(ostream& s, const vector<T>&) { s << "vector<T>"; return s; }
template<typename T, typename A>
ostream& operator<<(ostream& s, const vector<T, A>&) { s << "vector<T, A>"; return s; }
int main() {
myType<int, float> a; cout << stringify(a) << endl; // prints "myType"
cout << stringify(6) << endl; // prints "6"
vector<int> v(5); cout << stringify(v) << endl; // prints "{?}"
return 0;
}
Warum wird die Vorlage myType<>
Zeichenfolge erhalten, aber der Templat-vector<>
Typ nicht?
Für den vector<>
Typen erhalte ich den Standard {?}
stringification aber ich mag eindeutig eine der Überlastung am Boden genannt zu werden - genau wie mit myType<>
EDIT:
Die eigentliche Frage ist, Warum ist has_insertion_operator<vector<int>>
falsch?
Ich brauche dies auch in C++ 98
Und die operator<<
Überlastungen sollten nach stringify()
geliefert werden - wie bei myType<>
Es ist offensichtlich, warum der Vektor nicht beschriftet ist. Die Frage kann vereinfacht werden zu "Warum ist' has_insertion_operator> 'false?" –
user2079303
@ user2079303: Was ist "offensichtlich" darüber? Es gibt einen "ostream & operator" (ostream & s, const vector &) genau dort. –
@LightnessRacesinOrbit gut eigentlich hat er Recht - es ist die Eigenschaft der Schuld - es treibt die '' 'enable_if <>' '' und die SFINAE – onqtam