Checking at compile time if specified value is in a range of a type

后端 未结 4 1709
难免孤独
难免孤独 2021-01-21 17:17

Is it possible to check this:

template
struct X{};

What I mean by this is, is it possible to check that va

4条回答
  •  無奈伤痛
    2021-01-21 17:59

    No. Given your code, 300 is converted to a char by the compiler before you ever get to see it.

    The closest thing you can do is accept the argument into an integer parameter who's range is larger than your target type. Then check that the value will fit before converting. The only problem is signed versus unsigned, for which I don't think there's a general solution.

    But not to worry: it's not your class's job to make sure the arguments are being supplied correctly; that would be the job of a utility type that simply doesn't exist. For better or for worse, C++ doesn't provide a clean mechanism for this because it assumes the programmer won't make these mistakes.

提交回复
热议问题