1
4

2 回答 2

1

First of all, this:

remove_reference<unique_ptr<int>&>::type

Is just equivalent to this:

unique_ptr<int>

I do not see the need for the remove_reference there. To convince yourself, try the following:

#include <type_traits>
#include <memory>

static_assert(std::is_same<
    remove_reference<unique_ptr<int>&>::type, 
    unique_ptr<int>>::value, "!");

And you will see that the assertion does not fire (live example).

Most likely the reason for the compiler error you are getting is that you are not using the typename disambiguator in your function template:

template<typename K, typename V, typename M>
void moveValueForUniqueKey(M targetMap, K key, 
    typename remove_reference<unique_ptr<V>&>::type value) throw(char)
//  ^^^^^^^^
{
    // ...
}

But again, there is no reason to use remove_reference there:

template<typename K, typename V, typename M>
void moveValueForUniqueKey(M targetMap, K key, unique_ptr<V> value) throw(char)
//                                             ^^^^^^^^^^^^^
{
    // ...
}

Finally, keep in mind that dynamic exception specifications are deprecated in C++11.

于 2013-06-05T21:48:03.763 回答
1

Well first you would need typename since you are obtaining a type through a template argument:

template<typename K, typename V, typename M>
void moveValueForUniqueKey(
    M targetMap, K key, typename remove_reference<unique_ptr<V>&>::type value) throw(char)
    //                  ^^^^^^^^
{...}

But you don't need the signature remove_refrence<T&>::type. Why aren't you just using T?

template<typename K, typename V, typename M>
void moveValueForUniqueKey(M targetMap, K key, unique_ptr<V> value) throw(char)
{...}

std::unique_ptr cannot be copied, so you should simply move any lvalues into the parameter. For example, you have an invalid line in your main. Change this:

moveValueForUniqueKey(testMap, key1, move(val2));

to this

moveValueForUniqueKey(move(testMap), key1, move(val2));
//                    ^^^^^^^^^^^^^
于 2013-06-05T21:52:09.253 回答