Enforcing correct input/output of integers The problem:


Some types, like cstdint aliases or, at least purely theoretically, even std::size_t, may be (but don’t have to be) bound to char, signed char or unsigned char. In practice, std::int_least8_t seems to be often bound to signed char and std::uint_least8_t – to unsigned char. This seems odd, since semantically, all those types are supposed to represent integers rather than characters.
In case of variables of a character type, the &gt;&gt; operator writes the character code of the first non-whitespace character of the input stream into the variable, while the &lt;&lt; operator outputs a character of the character code equal to the value of the variable.
Therefore it may happen that if we, for example, declare a variable as int_least8_t and use the input operator or the output operator on it, then the results will be far from expected. This seems to be even more awkward since whether such aliases are bound to character types or not depends only on the implementation and is a priori unknown.


An example of the above problems: http://ideone.com/JgyFhR A proof that purely theoretically, this can even be the case for std::size_t: https://stackoverflow.com/questions/32915434

I’ve attempted to write a generic solution to all those problems:

#ifndef INTIO_H
#define INTIO_H

#include &lt;istream&gt;
#include &lt;ostream&gt;
#include &lt;type_traits&gt;
#include &lt;limits&gt;

template
&lt;class T, typename = typename std::enable_if&lt;std::is_integral&lt;T&gt;::value&gt;::type&gt;
class integer_IO
{
  T &amp;val;

public:

  integer_IO(T &amp;arg) : val(arg) {}
  integer_IO(T &amp;&amp;arg) : val(arg) {}

  friend std::istream &amp;operator&gt;&gt; (std::istream &amp;is, integer_IO&lt;T&gt; &amp;&amp;i)
  {
    using TT = decltype(+i.val);
    TT hlp;
    is &gt;&gt; hlp;
    TT constexpr minval = static_cast&lt;TT&gt;(std::numeric_limits&lt;T&gt;::min());
    TT constexpr maxval = static_cast&lt;TT&gt;(std::numeric_limits&lt;T&gt;::max());
    i.val = static_cast&lt;T&gt;(hlp &gt; maxval ? maxval : hlp &lt; minval ? minval : hlp);
    if(hlp &gt; maxval || hlp &lt; minval)
      is.setstate(std::ios::failbit);
    return is;
  }

  friend std::ostream &amp;operator&lt;&lt; (std::ostream &amp;os, integer_IO&lt;T&gt; const &amp;&amp;i)
  {
    os &lt;&lt; +i.val;
    return os;
  }
};

template
&lt;class T, typename = typename std::enable_if&lt;std::is_integral&lt;T&gt;::value&gt;::type&gt;
integer_IO&lt;T&gt; intIO(T &amp;arg)
{
  return integer_IO&lt;T&gt;(arg);
}

template
&lt;class T, typename = typename std::enable_if&lt;std::is_integral&lt;T&gt;::value&gt;::type&gt;
integer_IO&lt;T&gt; intIO(T &amp;&amp;arg)
{
  return integer_IO&lt;T&gt;(arg);
}

#endif


The usage of this wrapper is simple:

#include &lt;iostream&gt;
#include &lt;cstdint&gt;
#include "intIO.hpp"
using namespace std;

int twoplustwo()
{
  return 2+2;
}

int main()
{
  int_least8_t i;
  cin &gt;&gt; intIO(i);
  cout &lt;&lt; intIO(i) &lt;&lt; '\n';
  cout &lt;&lt; intIO(twoplustwo()) &lt;&lt; '\n';
}


What is your opinion of my code?
Avoid name collisions

#ifndef INTIO_H
#define INTIO_H


You should ideally prefix the include guard by something that is unlikely to cause a collision with any one using your library. As it stands now it is at risk of collision if some one else unluckily choose to use INTIO_H as their include guard.

Hide implementation details

To me it looks like the integer_IO class is not directly intended to be used by the user. In that case you should wrap it in an internal namespace so that the primary namespace that the user sees isn't cluttered with internal functions.

Naming

I think that the name integer_IO is kind of mixing two different case standards. To my knowledge there are kind of two major standards emerging, one is to use CameCase in which you would name your class IntegerIO and the other one is to use inderscore instead of space and all lower case so you would have integer_io. If you're going to allow upper case in names, then I would at least suggest that you use leading upper case like so Integer_IO. Any of the above are easier on my eyes than the current name.

Also I think that the intIO functions would be better named asInt:

std::cin&gt;&gt;asInt(x);


Universal references

This here is a universal reference, the parameter arg will inherit whatever qualifiers the constructor was called with. 

  integer_IO(T &amp;&amp;arg) : val(arg) {}


If the constructor was called with a temporary like so auto iio = integer_IO(x + y) where x and y are int arguments, then arg would deduce to int&amp;&amp;. Which is an r-value reference, you are then storing the pointer to this temporary into val which refers to... you guessed it something that might be dangling as soon as the constructor returns.

The other constructor:

  integer_IO(T &amp;arg) : val(arg) {}


will not bind to temporaries because it must be able to take the address of the argument. Other than that it will bind to reference to const because T will be deduced to const T. So this constructor covers all legal use cases that the one with universal reference does, so you can remove either one. I suggest you nuke the universal one because it is slightly harder to understand.

Stream operators

Your two stream operators:

friend std::istream &amp;operator&gt;&gt; (std::istream &amp;is, integer_IO&lt;T&gt; &amp;&amp;i)
friend std::ostream &amp;operator&lt;&lt; (std::ostream &amp;os, integer_IO&lt;T&gt; const &amp;&amp;i)


are using r-value references (NOTE: They are not universal references). Note that const r-value reference doesn't make any sense.

Anyway, I assume that this is because you only want to allow usage on the form:

std::cout&lt;&lt;intIO(x);


and prohibit some one from doing:

auto foo = intIO(x);
std::cout&lt;&lt;foo;


However I do not see the point of prohibiting this use at the cost of making the implementation harder to read (I had to reason about those functions for quite some while before I was sure they work and why they work). You could just as well have 

friend std::istream &amp;operator&gt;&gt; (std::istream &amp;is, integer_IO&lt;T&gt; i)
friend std::ostream &amp;operator&lt;&lt; (std::ostream &amp;os, const integer_IO&lt;T&gt;&amp; i)


and your code would be easier to follow and would generate the same code. And allow the above usage syntax. 

Reading into a temporary??

This tickled my funny bone:

template
&lt;class T, typename = typename std::enable_if&lt;std::is_integral&lt;T&gt;::value&gt;::type&gt;
integer_IO&lt;T&gt; intIO(T &amp;&amp;arg)
{
  return integer_IO&lt;T&gt;(arg);
}


As you are using universal references this means that arg will bind to anything and retain it's qualifiers. Even r-value references... which means that the following will compile and run doing some manner of undefined behaviour:

std::cin&gt;&gt;intIO(3);


Jolly. 

In summary

I can see how this can have some uses in template code but I believe that your implementation is too complicated. My advice is to stop trying to be fancy with &amp;&amp; and just make something that works. 

I would probably have implemented it like this:

#include &lt;istream&gt;
#include &lt;ostream&gt;
#include &lt;iostream&gt;
#include &lt;limits&gt;
#include &lt;type_traits&gt;
#include &lt;cstdint&gt;

#define ENABLE_IF_INTEGRAL(T)\
typename = typename std::enable_if&lt;std::is_integral&lt;std::decay_t&lt;T&gt;&gt;::value&gt;::type

namespace detail{
    template&lt;class T, ENABLE_IF_INTEGRAL(T)&gt;
    struct wrapper{
        T&amp; x;
        wrapper(T&amp; xx) : x(xx){};

        friend std::istream&amp; operator &gt;&gt; (std::istream&amp; is, wrapper&lt;T&gt; w){
            auto read = +w.x;
            is&gt;&gt;read;
            w.x = static_cast&lt;std::decay_t&lt;T&gt;&gt;(read);
            if(w.x != read){
                is.setstate(std::ios::failbit);
                //C++11 behaviour
                constexpr auto max = std::numeric_limits&lt;std::decay_t&lt;T&gt;&gt;::max();
                constexpr auto min = std::numeric_limits&lt;std::decay_t&lt;T&gt;&gt;::min();
                w.x = static_cast&lt;T&gt;(read &lt; min ? min : max);
            }
            return is;
        }
    };
}

template&lt;class T, ENABLE_IF_INTEGRAL(T)&gt;
auto intoInt(T&amp; x){ return detail::wrapper&lt;T&gt;(x);}

template&lt;class T, ENABLE_IF_INTEGRAL(T)&gt;
auto asInt(T x){ return +x; }


#undef ENABLE_IF_INTEGRAL    

int oneplusone(){return 1 + 1;}

int main() {
    char foo;

    // Shouldn't compile
    //std::cin&gt;&gt;asInt(foo);
    //std::cin&gt;&gt;asInt(3);
    //std::cin&gt;&gt;intoInt(3);
    //std::cin&gt;&gt;intoInt(std::move(foo));
    //std::cout&lt;&lt;intoInt(std::move(foo));
    //std::cout&lt;&lt;intoInt(3);
    //std::cout&lt;&lt;intoInt(foo);

    // Readable into
    std::cin&gt;&gt;intoInt(foo);

    // Check status
    std::cout&lt;&lt; (std::cin.fail() ? "failed":"success")&lt;&lt;std::endl;

    // Binds to reference
    auto&amp; ref = foo;
    std::cout&lt;&lt;asInt(ref)&lt;&lt;std::endl;

    // Binds to const reference
    const auto&amp; cref = foo;
    std::cout&lt;&lt;asInt(cref)&lt;&lt;std::endl;

    // Binds to r-value reference
    std::cout&lt;&lt;asInt(std::move(foo))&lt;&lt;std::endl;

    // Binds to value returned function call (r-value really)
    std::cout&lt;&lt;asInt(oneplusone())&lt;&lt;std::endl;

    // Binds to literal
    std::cout&lt;&lt;asInt(31)&lt;&lt;std::endl;

    return 0;
}


In addition to being shorter and easier to comprehend, it also prohibits: std::cin&lt;&lt;asInt(3); from happening.