Why does the template instance constructor override the default instance constructor?

Change Updated Code:

class Any
{
public:
    Any()
    {
    }

    Any(const Any &other)
    {

    }

    Any(Any &other) // added per Ben answer
    {
    }

    Any(Any &&other)
    {
    }

    Any(const char *value)
    {
    }

    template<typename T>
    Any(const T &value)
    {
    }

    template<typename T>
    Any(T &&value)
    {
        cout << "move ctor" << endl;
    }

    template<typename T>
    Any(const vector<T> &value)
    {
    }

    template<typename T>
    Any(vector<T> &&value)
    {
    }
};

int main(int argc, char *argv[])
{
    vector<string> numbers;
    numbers.push_back("one");
    numbers.push_back("two");
    numbers.push_back("three");
    numbers.push_back("four");

    Any anyNumbers(numbers);
    Any anyNumbersCopy = anyNumbers;

    return 0;
}


prints:

"move ctor"

Why is this happening?

Is there a way to force the default copy constructor to be called instead of the const & constructor pattern?

I would like to avoid creating an explicit template constructor if possible, so that I can still implicitly build a class like this:

Any number = 5;
+1
source share
1 answer

Perhaps your real code is more like this?

class Any
{
public:
    Any(){}

    Any(const Any &other)
    {
    }

    template<typename T>
    Any(T &&other)
    {
    }
};

In this case, the template is better suited for Any& other(not const!). Then the solution should provide constructor overload without a constructor without a template:

class Any
{
public:
    Any(){}

    Any(const Any &other)
    {
    }

    Any(Any &other)
    {
    }

    template<typename T>
    Any(T &&other)
    {
    }
};
+5

All Articles