Can I enforce in compile time that the function is never called?

  • A+
Category:Languages

I want to prevent implicit conversions from std::string to std::filesystem::path or boost::filesystem::path.

As far as I know there is no way to modify system headers to make constructors explicit.

So I thought that I'll create a overrides of my internal api functions accepting std::string instead of fileystem::path and call assert(false) inside.

But later I started wondering that the compiler should know if given function declaration is ever referenced, so hypothetically it could detect call to such override at compile time instead of runtime and warn or fail the compilation.

Is my thinking correct? Is there any way to prevent calls to such functions at compile time?

Best, Piotr

 


You can declare but not define your conversion. Better yet, you can declare the function as deleted. If it is ever called, you will get an error at compile-time.

void f(std::filesystem::path p) {     // ... }  void f(std::string) = delete; // explanation 

Toy example

#include <iostream>  struct path {     path(std::string) {} // OOPS, not explicit! };  void f(path p) {     std::cout << "f(path)/n"; }  void f(std::string) = delete;   int main(int argc, char** argv) {     std::string s = "/dev/null";     //f(s);     // error: use of deleted function 'void f(std::__cxx11::string)'     f(path{s}); // OK } 

(demo)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: