I was reading about nullptr and doing workout on g++ and also on VS2010.
When I did
#include
using namespace std;
aut
I ran into this problem while I was writing some type-parameterized test code (using templates). I needed to print a value of type T, where nullptr_t was a valid type for T. I came up with a solution where the value to be printed was wrapped inside a printable template function. This function then makes use of template specialization to provide the desired behavior when a nullptr_t is used.
#include
#include
template struct Printable
{
Printable(const T& val) : val(val) {}
void print(std::ostream& out) const {out << val;}
const T& val;
};
template <> struct Printable
{
Printable(nullptr_t) {}
void print(std::ostream& out) const {out << "null";}
};
template
Printable printable(const T& value) {return Printable(value);}
template
std::ostream& operator<<(std::ostream& out, const Printable& p)
{
p.print(out);
return out;
}
int main() {
std::cout << printable(42) << " " << printable(nullptr) << "\n";
return 0;
}
Ideone link