2

理解しようとしている C++ のコードを取得しましたが、インターネットで検索しても把握できない部分が 1 つあります。私の質問は、これが何を意味するかです:

if (!(T() < x))

構造体で:

struct Positive_Check_Except
{
    template<typename T>
    static bool validate(const T& x)
    {
    if (!(T() < x))
        throw check_error(std::to_string(x) + " not positive exception");
        return true;
    }
};
4

1 に答える 1

4

Step by step:

  1. T() constructs a temporary, value-initialized instance of T.
  2. T() < x compares x, which is a T instance, with the temporary T() using less-than operator<.
  3. !(T() < x) negates the result of that comparison

It is checking that the argument x is greater than a value-initialized T, and throwing an exception if this is not the case.

It relies on T being a built-in type (in which case, value initialization is zero initialization), or a default constructible user defined type (in which case value initialization calls the default constructor). It also requires that an operator< exits that can compare two T instances and return something convertible to bool.

See here for more on value initialization.

于 2013-08-18T09:16:57.617 に答える