简体   繁体   中英

C++ - how to resolve function overload ambiguity

consider following simple class (please no debates about usefulness):

class Container
{
    public:
        Container(const long long &val); //construct the container with a long long
        Container(const long double &val); //construct the container with a long double
        Container(const std::string &val); //construct the container with a string
        Container(const Container &val); //copy constructor, implemented as copy and swap

        //explicit conversions are also included for other data types
        explicit operator long long() const; //explicit conversion to long long

    private:
        int dataType;
        void *data;
};

And to construct the object, I would call:

Container cont(20); //or
Container cont2("some string");

But the compiler tells me he cannot resolve the ambiguous constructor call for int.

This leads me to my question, what is the best and cleanest way to resolve this ambiguity.
Should I use some sort of templatized constructor looking somewhat like this:

Container<int> cont(20);

Or use an explicit cast or a dummy parameter?

The templatized way looks like a compromise I could accept, though I'm sure the actual call would look different.

Well thanks for any insights!

Just add a constructor for int that disambiguates it:

Container(int i)
: Container(static_cast<long long>(i)) // or whichever version you want
                                       // to call
{ }

You may use a constructor templated by the type:

class Container {
    template <class T> Container (const T& rhs);
};

See the implementation of "any" in Boost for an example similar to what you want to do: http://www.boost.org/doc/libs/1_58_0/doc/html/boost/any.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM