0

在下面的代码中:

template<class Key, class Value>
    class Pair
    {
    private:
        std::pair<Key,Value> body_;
    public:
        //No cpy ctor - this generated by compiler is OK
        Pair(Key&& key,Value&& value)
        {
            body_.first = key;
            body_.second = value;
        }

        Pair(Pair<Key,Value>&& tmpPattern)
        {
            body_.swap(tmpPattern.body_);
        }

        Pair& operator=(Pair<Key,Value> tmpPattern)
        {
            body_.swap(tmpPattern.body_);
            return *this;
        }

                };

    template<class Key, class Value>
    Pair<Key,Value> MakePair(Key&& key, Value&& value)
    {
        return Pair<Key,Value>(key,value);
    }

由于某些奇怪的原因,当我尝试运行 MakePair 时出现错误,为什么?天知道...

int main(int argc, char** argv)
{
auto tmp = MakePair(1, 2);
}

这是这个错误:
错误错误 C2665:Pair::Pair':3 个重载都不能转换所有参数类型

我只是不明白要执行什么转换?

4

2 回答 2

0

您需要将值传递给MakePair,而不是类型。试试这个:

int a = 1;
int b = 2;
auto tmp = MakePair( a, b ); // creates a Pair<int,int> with the values of a and b
于 2010-11-22T12:27:26.287 回答
0

return Pair<Key,Value>(std::forward<Key>(key),std::forward<Value>(value));

虽然我不太确定为什么右值转发不是隐式的。

编辑:哦,我想我明白了。这样,您仍然可以将右值引用传递给接受值的函数。

于 2010-11-22T16:28:33.280 回答