How to resolve this call for an ambiguous constructor by making one of them explicit?

In the following code, I create an instance Nodeby passing an instance Point. for example Node{{0, 1}};, however, the constructor call is Nodeambiguous. My guess is that {0, 1}it can also be understood as two intviews char, and {char, char}also refers to the constructor std::stringin the form std::initializer_list<char>.

I want to save the opportunity in a constructive Nodeway Node{{0, 1}}, as well as save the conversion from std::stringto Node, preferably in the form Node{std::string{"0,1"}}or something like that. Is there a way to call a constructor that accepts a string only if this points to this? or just disable the constructor std::string std::initializer_list<char>?

Thanks in adavance.

#include <string>

class Point
{
public:
    Point() {};
    Point(int x, int y) : x(x), y(y) {}
private:
    int x;
    int y;
};

class Node
{
public:
    Node(const std::string& str) {}
    Node(const Point& dot) : dot(dot) {}
private:
    Point dot;
};

int main()
{
    Node{{0, 1}};
    return 0;
}

:

/Users/cpp_sandbox.cpp:24:5: error: call to constructor of 'Node' is ambiguous
    Node{{0, 1}};
    ^   ~~~~~~~~
/Users/cpp_sandbox.cpp:16:5: note: candidate constructor
    Node(const std::string& str) {}
    ^
/Users/cpp_sandbox.cpp:17:5: note: candidate constructor
    Node(const Point& dot) : dot(dot) {}
    ^
1 error generated.
[Finished in 0.1s with exit code 1]
[shell_cmd: g++ -std=c++11 "/Users/cpp_sandbox.cpp" -o "/Users/cpp_sandbox"]
[dir: /Users]
[path: /usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/X11/bin:/Applications/SquishCoco/:/Library/TeX/texbin]
+4
1

, , . Node Point. Point:

class Node: public Point
{
public:
    using Point::Point; // constructor inheritance
    Node(std::string str) {}
};

Node{0, 1}; // note that Node{{0, 1}} will invoke the string ctor

Node{"test"};

.

:

#include <iostream>
#include <string>

class Point
{
public:
    Point() {};
    Point(int x, int y) : x(x), y(y) {std::cout << __PRETTY_FUNCTION__ << '\n';}
private:
    int x{};
    int y{};
};

class Node: public Point
{
public:
    using Point::Point;
    Node(const std::string&) {std::cout << __PRETTY_FUNCTION__ << '\n';}
};

int main()
{
    Node{0, 1};
    Node{"test"};
}

Live on Coliru

, Node{{0, 1}} Node::Node(const std::string&) , - Node::Node(const std::string&) ( Point::Point(int, int), ' t ). Node::Node(const Point&) - Point ( ).

+4

Source: https://habr.com/ru/post/1684010/


All Articles