1

Recently I was using functions in <filesystem>, e.g. std::filesystem::exists. These functions accept std::filesystem::path. I noticed passing const char* like "/abc" to function like std::filesystem::exists works, e.g. std::filesystem::exists("/abc")

My question is, it seems like when passing const char* to std::filesystem::exists, we are doing some implicit conversion from const char* to filesystem::path.

  1. Which constructor handles this on filesystem::path class?
  2. How can I write a constructor for this type of conversion? Below code doesn't seem to work, and I'm not sure what's wrong. (I'm a bit new to C++).
class A {
  A(const char*& msg) {
    std::cout << msg << std::endl;
  }
};

void func(const A& p) {
}

int main(int argc, const char * argv[]) {
  func("123"); // No matching function for call to 'func'
  return 0;
}

1 Answer 1

1

First of all, make the constructor Public.

And secondly constructor for A in your code is taking const char*& which is reference to const char*, so const char* won't be implicitically converted to A because const char*& is lvalue reference and const char* is rvalue (basically nameless temporary)

Try this it will work

#include<iostream>
class A {
public:
  A(const char* msg) {
    std::cout << msg << std::endl;
  }
};

void func(const A& p) {
}

int main(int argc, const char * argv[]) {
  func("123"); // No matching function for call to 'func'
  return 0;
}

Which constructor handles this on filesystem::path class

According to cppreference, (5) constructor

template< class Source > path( const Source& source, format fmt = auto_format );

takes care of implicit type conversions from const char* to std::filesystem::path

Sign up to request clarification or add additional context in comments.

5 Comments

Do answer the first part as well.
Ohh, nice. Why doesn't const char*& work? Is there a term for this kind of constructor that I can search for, e.g. is it a copy constructor?
@Daiwei it is a parameterised constructor.
The end of your answer is incorrect. string_type is std::string or std::wstring, so you need a conversion from const char [4] ("abc") to string_type and then to path for exists, which are two user-defined conversions, and the standard only allow one user-defined conversion in an implicit conversion sequence. The constructor used is the 5th one in the link you posted: template< class Source > path( const Source& source, format fmt = auto_format );
@Holt thanks for pointing it out, yeah my mistake, updated the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.