4

The class foo contains a private tuple member. I want to get reference to an element of this tuple using a getElement<I>(). I came to this solution but it doesn't work when the object is passed to the constructor of another class bar:

#include <tuple>

template<class... Args>
class foo {
    std::tuple<Args...> tup_;

    public:
    foo(Args... args) : tup_ {args...} {};

    template<size_t I>
    const typename std::tuple_element<I, std::tuple<Args...>>::type &
    getElement() const {return std::get<I>(tup_);}
};

template<class T>
class bar;

template<class T, class U>
class bar<foo<T,U>> {
    public:
    bar(foo<T,U> f) {
       auto j = f.getElement<0>(); // this is an ERROR!!! Line 22
    }
};


int main()
{
   foo<int, char> f(12,'c');
   auto j = f.getElement<0>(); // but this is OK!

   bar<decltype(f)> b(f);

   return 0;
}

compiler output:

main.cpp: In constructor 'bar<foo<T, U> >::bar(foo<T, U>)':                                                                                                                                                                      
main.cpp:22:33: error: expected primary-expression before ')' token                                                                                                                                                              
        auto j = f.getElement<0>(); // this is an ERROR!!!                                                                                                                                                                       
                                 ^                                                                                                                                                                                               
main.cpp: In instantiation of 'bar<foo<T, U> >::bar(foo<T, U>) [with T = int; U = char]':                                                                                                                                        
main.cpp:32:24:   required from here                                                                                                                                                                                             
main.cpp:22:29: error: invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'                                                                                                         
        auto j = f.getElement<0>(); // this is an ERROR!!! 
Vahid
  • 312
  • 3
  • 13

1 Answers1

4

You must warn the compiler that getElement is a template method. And to do it you must specify the template keyword, eg:

f.template getElement<0>()

This because otherwise the compiler tries to parse the code as f.getElement < 0 so that it tries to call the binary operator< on f.getElement and 0 which is not what you want to do.

Jack
  • 131,802
  • 30
  • 241
  • 343