mardi 30 juin 2015

C++ variadic template, recursion decltype

I know there are already a lot of questions concerning this topic, but so far I found no response that satisfactorily answers the following questions. Given the following code.

#include <utility>

template<typename T, typename K>
std::pair<T, K> pair()
{
    return std::pair<T, K>();
}

template<typename T, typename...K>
std::pair<T, decltype(pair<K...>())> pair()
{
    return std::pair<T, decltype(pair<K...>())>();
}


int main(int argc, char **argv)
{
    auto m2 = pair<int, int>();
    auto m3 = pair<int, int, int>();    
    auto m4 = pair<int, int, int, int>();   // <- Compile Error here
    return 0;
}

A call to

pair<int, int>() 

shall return an object

std::pair<int, int>

and this works perfectly for up to three template parameters. As mentioned in the code calling the pair function with four template parameters fails and g++ (5.1.0) returns the following error.

main.cpp: In function 'int main(int, char**)':
main.cpp:20:37: error: no matching function for call to 'pair()'
  auto m4 = pair<int, int, int, int>(); // <- Compile Error here
                                     ^
main.cpp:4:17: note: candidate: template<class T, class K> std::pair<_T1, _T2> pair()
 std::pair<T, K> pair()
                     ^
main.cpp:4:17: note:   template argument deduction/substitution failed:
main.cpp:20:37: error: wrong number of template arguments (4, should be 2)
  auto m4 = pair<int, int, int, int>(); // <- Compile Error here
                                     ^
main.cpp:10:38: note: candidate: template<class T, class ... K> std::pair<T, decltype (pair<K ...>())> pair()
 std::pair<T, decltype(pair<K...>())> pair()
                                      ^
main.cpp:10:38: note:   template argument deduction/substitution failed:
main.cpp: In substitution of 'template<class T, class ... K> std::pair<T, decltype (pair<K ...>())> pair() [with T = int; K = {int, int, int}]':
main.cpp:20:37:   required from here
main.cpp:10:33: error: no matching function for call to 'pair()'
 std::pair<T, decltype(pair<K...>())> pair()
                                 ^
main.cpp:4:17: note: candidate: template<class T, class K> std::pair<_T1, _T2> pair()
 std::pair<T, K> pair()
                 ^
main.cpp:4:17: note:   template argument deduction/substitution failed:
main.cpp:10:33: error: wrong number of template arguments (3, should be 2)
 std::pair<T, decltype(pair<K...>())> pair()
                                 ^

Therefore my questions are:
- Is this issue g++ related?
- What is the designated way to solve this problem?

Thanks four your help!

Aucun commentaire:

Enregistrer un commentaire