Tarun Maganti Tarun Maganti - 22 days ago 8
C++ Question

Can we send pair a template argumrent another pair

Can we use pair as an argument for another pair in C++.

Here is a test program to do that.

#include <iostream>
#include <utility>

int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<int**,<std::pair<int,int> > > i(p,m);
std::cout<<i[t];

return 0;
}


This is the error, I am getting.

Test.cpp: In function ‘int main()’:
Test.cpp:12:45: error: template argument 2 is invalid
std::pair<int**,<std::pair<int,int>>> i(p,m);
^


If I changed the format of declaration and wrote the program in the following way,

#include <iostream>
#include <utility>

int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<
int**,
<
std::pair<
int,
int
>
>
> i(p,m);
std::cout<<i[t];

return 0;
}


There is an additional error.

Test.cpp: In function ‘int main()’:
Test.cpp:20:7: error: template argument 2 is invalid
> i(p,m);
^
Test.cpp:20:14: error: expression list treated as compound expression in initializer [-fpermissive]
> i(p,m);


What might be the issue and how to solve it?




On a side note, I did a program and compiled it in an very old Dev-c++ compiler on a windows 7 machine which used a code similar to the above and it ran perfectly fine. It was a lab program in my college which had only that compiler.

The above code, I ran on both windows 7 and Ubuntu 16.04 using GNU g++ 5.4.0

Ideone: Link to the actual program for reference

You might also have a look at the actual error, I faced in the above link.

Answer

There are two problems with your code.

  1. You have a superfluous pair of angle brackets in your template instantiation.
  2. The cout parameter makes no sense

#include <iostream>
#include <utility>

int main()
{
    std::pair<int,int> m;
    m=std::make_pair(1,3);
    int r = 3;
    int *q = &r;
    int **p =&q;
    int **t = p;
    std::pair<
                int**,
                // < Omit this
                    std::pair<
                                int,
                                int
                                >
                            // > also this
                        > i(p,m);
    // std::cout<<i.[t]; indexing with a pointer value doesn't make sense
    // i. for a pair doesn't make sense, specify either first or second
    std::cout<<i.first[0]; // Did you mean something like this

    return 0;
}

Check the compiling version live