通过模板成员函数访问私有元组元素
Access to private tuple element through a template member function
类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
这不是您想要执行的操作。
相关文章:
- 如何基于元组元素进行递归?
- 元组元素是只读的?
- 在 Hana 中满足谓词的元组元素的索引序列
- 如何部分专业化功能以用元组元素作为参数调用功能
- 匹配部分专用化以按类型替换元组元素
- 仅当元组中存在该类型时,将功能应用于元组元素
- 获取std ::元组元素作为std ::变体
- 获取对元组元素的引用
- 用std :: apply迭代元组元素
- 检查是否所有 std::元组元素都满足条件 + 设计问题
- 查找元组元素 C++ 的最大值
- 如何按类型为元组元素创建专用函数
- 在元组向量中查找特定的元组元素
- 将多态函数应用于每个元组元素的结果类型
- 推导出 C++11 中元组元素的类型
- 通过模板成员函数访问私有元组元素
- 通过索引 C++11 访问元组元素
- 按类型获取元组元素(pre C++0x)
- 可变模板:选择具有适当方法的元组元素类型
- 获取元组元素类型的索引?