1

编辑更新代码:

class Any
{
public:
    Any()
    {
    }

    Any(const Any &other)
    {

    }

    Any(Any &other) // added per Ben's 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;
}


印刷:

“移动 ctor”

为什么会这样?

有没有办法强制调用默认的复制构造函数而不是模板化的 const& 构造函数?

如果可能的话,我想避免使模板构造函数显式,以便我仍然可以像这样隐式构造类;

Any number = 5;
4

1 回答 1

5

也许您的真实代码看起来更像这样?

class Any
{
public:
    Any(){}

    Any(const Any &other)
    {
    }

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

在这种情况下,模板更适合Any& other(不是const!)。那么解决方案是提供一个非常量非模板复制构造函数重载:

class Any
{
public:
    Any(){}

    Any(const Any &other)
    {
    }

    Any(Any &other)
    {
    }

    template<typename T>
    Any(T &&other)
    {
    }
};
于 2013-07-29T22:55:36.740 回答