c++ - How to detect cast from bool -
c++ - How to detect cast from bool -
i found error in code think should marked warning. compiled /w4 don't show warning (only unreferenced formal parameter).
#include <cstdio> void a(int item, unsigned int count, unsigned team_count) { printf("a, count, team count\n"); } void a(int item, unsigned int count=1, bool is_team=true) { printf("a, count, is_team\n"); homecoming a(item, count, is_team ? count : 0); } int main() { a(0, false); // <- bool unsigned int homecoming 0; }
here bool casted unsigned int. there way observe that? tried cppcheck don't find this.
the standard says acceptable §4.7/p4 integral conversions:
if source type bool, value false converted 0 , value true converted one.
regarding how observe (since it's not error) , depending on use-case, either clang-tooling or write wrapper template deduction magic on lines of:
#include <cstdio> #include <type_traits> template<typename t, typename u> void a(int item, t, u) { static_assert(!std::is_same<t, unsigned int>::value || (!std::is_same<u, unsigned int>::value && !std::is_same<u, bool>::value), "something wrong"); } template<> void a(int item, unsigned int count, unsigned int team_count) { printf("a, count, team count\n"); } template<unsigned int count = 1, bool is_team = true> void a(int item, unsigned int, bool) { printf("a, count, is_team\n"); homecoming a(item, count, is_team ? count : 0); } int main() { // a(0, false); - not acceptable // a(0, 22); - not acceptable a(0, static_cast<unsigned int>(2), false); a(0, static_cast<unsigned int>(33), static_cast<unsigned int>(45)); homecoming 0; }
example
note base of operations template deduction mechanism doesn't require c++11, although functions used above do.
c++ visual-studio-2008
Comments
Post a Comment