Category : explicit

I have a class ‘Entity’. It has a user-defined constructor (implicit) with one argument as shown below. class Entity { public: Entity(int a) { std::cout << a << std::endl; } Entity(const std::string& s) { std::cout << s << std::endl; } }; int main() { Entity e1 = (10, 20); Entity e2 = (10, 20, 30); ..

Read more

#include <iostream> #include <string> struct mystruct{ mystruct(std::string s){ std::cout<<__FUNCTION__ <<" String "<<s; } explicit mystruct(bool s) { std::cout<<__FUNCTION__<<" Bool "<<s; } }; int main() { const char* c ="hello"; mystruct obj(c); return 0; } output: mystruct Bool 1 Why const char* implicitly converted to bool rather than std::string, though constructor requires explicit type ? How ..

Read more

what is the usecase for explicit (bool) C++20 introduced explicit (bool) which conditionally selects at compile-time whether a constructor is made explicit or not. Below is an example which I found here. struct foo { // Specify non-integral types (strings, floats, etc.) require explicit construction. template <typename T> explicit(!std::is_integral_v<T>) foo(T) {} }; foo a = ..

Read more