Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

like image 664
user1782685 Avatar asked Dec 18 '22 18:12

user1782685


1 Answers

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)

like image 196
YSC Avatar answered Jan 11 '23 23:01

YSC