通过模板成员函数访问私有元组元素

Access to private tuple element through a template member function

本文关键字:元组 元素 访问 函数 成员      更新时间:2023-10-16

foo包含一个私有元组成员。我想使用 getElement<I>() 获取对该元组元素的引用。我得出了这个解决方案,但是当对象传递给另一个类的构造函数时,它不起作用 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;
}

编译器输出:

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

必须警告编译器getElement是模板方法。为此,您必须指定template关键字,例如:

f.template getElement<0>()

这是因为否则编译器会尝试将代码解析为f.getElement < 0,以便尝试在f.getElement上调用二进制operator<,并0这不是您想要执行的操作。