简体   繁体   中英

How to use the auto and decltype keywords to ease template argument deduction?

I am implementing the Merge sort algorithm. The problem is when I try to use a vector of automatically deduced types within the algorithm.

template <typename TIterator, typename TCompare>
void mergeSort(TIterator begin, TIterator end, TCompare criterium)
{
     //...
     auto help = *begin;                // help is a value (not a reference)
     QVector<decltype(help)> leftPart;  // now decltype(help) is also a value
     //...                              // and not a reference
}

This works.

But once I make the algorithm pass the TIterators by constant reference, I get an error which I never got in my whole life:

template <typename TIterator, typename TCompare>
void mergeSort(const TIterator& begin, const TIterator& end, TCompare criterium)
{
     //...
     auto help = *begin;                    // help is a value (not a reference)
     QVector<decltype(help)> leftPart;  // now decltype(help) is also a value
     //...
}

results in:

In function 'void mergeSort(const TIterator&, const TIterator&, TCompare)':
internal compiler error: in type_unification_real, at cp/pt.c:14176

I am using g++ 4.6.3 on Ubuntu

What went wrong?

An internal compiler error occurs whenever the compiler fails , which means that you found a bug. This is the reason while early adoption of new standards is usually called the bleeding edge : sometimes, it makes you bleed ;)

There might be something wrong with your code, or there might not. It's not possible to tell from this output alone. What is certain is that the compiler does not support it so you might want to change it instead.

In particular, lookup std::iterator_traits<> to see all the things you can deduce from an iterator's type:

typename std::iterator_traits<TIterator>::value_type help = *begin;
                                     // ::reference
                                     // ::pointer
                                     // ...

By circumventing the automatic deduction, you will probably be able to get past the compiler bug.


Note: if you wish to report the bug, which is certainly laudable, you will be asked to produce a preprocessed file reproducing the issue. This file should be as small as possible. It can be generated using -E on the gcc command line and generally ends up with the .ii extension.

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