string
Conversion#include <sstream> // Not <strstream> std::ostringstream oss; oss << i; std::string ostr = oss.str();
std::string int2str(int i) { std::ostringstream oss; oss << i; return oss.str(); } std::string istr = int2str(801);
operator <<
must be defined for the value.
std::string bool2str(bool val) { std::ostringstream oss; oss << val; return oss.str(); } |
std::string char2str(char val) { std::ostringstream oss; oss << val; return oss.str(); } |
std::string int2str(int val) { std::ostringstream oss; oss << val; return oss.str(); } |
std::string float2str(float val) { std::ostringstream oss; oss << val; return oss.str(); } |
and so on |
std::string val2str(VALUE_TYPE val) { std::ostringstream oss; oss << val; return oss.str(); } VALUE_TYPE = int string str = val2str(801)
>>
vs. > >
.
template <class T1, class T2, ... >
.
int
not the value 801
.
typename
is less confusing.
template <typename valueT> std::string val2str(valueT v) { std::ostringstream oss; oss << v; return oss.str(); }
std::string istr = val2str(801);
char
does not exactly match int
.
const char
does not exactly match char
.
T &
does not exactly match T
.
f(1.0, 1)
does not match the template function definition
template < typename t1 > f(t1 x, t1 y) { . . . }
because
x = 1.0
binds t1
to type float
.
y = 1
binds t1
to type int
.
float
is not int
.
f(1.0, 1)
does match the template function definition
template < typename t1, template t2> f(t1 x, t2 y) { . . . }
producing the consistent template parameter binding
x = 1.0
binds t1
to type float
.
y = 1
binds t2
to type int
.
template <class T> T oops(int i) { T tval; // whatever return tval; } // What is T? oops(1);
template <typename T> void oops(T i, T j) { // whatever } int i = 3; unsigned j = 4;oops(i, j)// An int isn't an unsigned. struct P { }; struct C : P { }; P p; C c;oops(p, c);// A P isn't a C.
const
s and reference types are a great source type-matching
problems.
export
won't help.
.h
files.
char
and an int
.
string
-to-x Problematoi()
solves this problem for int
values.
atoi()
isn't standard.
int
?
std::istringstream iss(valstr); iss >> val;
operator >>
must be defined for the value's type.
template <typename valT> valT val2str(const std::string & vstr) { std::istringstream iss(vstr); valT v; iss >> v; return v; }
valT
.
< >
after the function name.
int i = val2str<int>(istr);
std::vector<int> ivec
.
template<class FTP1, class FTP2, ...> FTP1 f ( FTP2 a1, ...) { ... } f<T1, T2, ...>(arg1, arg2, ...);
template<class T> void f(T a1, T a2) { ... }f(1, 1.0);// call 1 f<double>(1, 1.0); // call 2
T
is both an int
and a float
.
int
and float
convert to double
.
template < type-spec T1, type-spec T2, ...>
template<int size> void t(int i) { int iarray[size]; iarray[i] = i; } int main() { t<10>(3); }
This page last modified on 17 November 2003.