2016-04-22 9 views
4

Die Klasse enthält ein privates Tupel-Element. Ich möchte Bezug auf ein Element dieses Tupels mit einem getElement<I>() bekommen. Ich kam zu dieser Lösung, aber es funktioniert nicht, wenn das Objekt an den Konstruktor einer anderen Klasse übergeben wird bar:Zugriff auf privates Tupel-Element über eine Template-Element-Funktion

#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 Ausgabe:

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!!! 
+0

'f.template getElement <0>();' –

+0

@PiotrSkotnicki danke, ich wusste nicht über diese Syntax. aber was bedeutet das für den Compiler? – Vahid

Antwort

4

Sie müssen den Compiler warnen, dass getElement ein Vorlagenmethode. Und, es zu tun, müssen Sie die template Schlüsselwort angeben, zum Beispiel:

f.template getElement<0>() 

Dies, weil sonst der Compiler den Code als f.getElement < 0 so zu analysieren versucht, dass es die binäre operator< auf f.getElement und 0 denen zu nennen versucht ist nicht das, was Sie möchte tun.

Verwandte Themen