【问题标题】:Access to private tuple element through a template member function [duplicate]通过模板成员函数访问私有元组元素[重复]
【发布时间】:2016-04-22 13:23:03
【问题描述】:

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

【问题讨论】:

  • f.template getElement&lt;0&gt;();
  • @PiotrSkotnicki 谢谢,我不知道这种语法。但这对编译器意味着什么?

标签: c++ templates c++11 tuples


【解决方案1】:

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

f.template getElement<0>()

这是因为否则编译器会尝试将代码解析为f.getElement &lt; 0,以便尝试在f.getElement0 上调用二进制文件operator&lt;,这不是您想要做的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多