说有两个功能:
void ff( const std::tuple<const int&> ) { }
template < typename TT >
void gg( const std::tuple<const TT&> ) { }
并调用这些函数:
int xx = 0;
ff( std::tie( xx ) ); // passes
gg( std::tie( xx ) ); // FAILS !!
GCC 4.7.2 编译最后一行失败,报如下错误提示:
note: template argument deduction/substitution failed:
note: types ‘const TT’ and ‘int’ have incompatible cv-qualifiers
note: ‘std::tuple<int&>’ is not derived from ‘std::tuple<const TT&>’
第一个问题是这是否符合 C++11 标准,如果不符合,那为什么?
此外,为了克服这个问题,需要将 const 引用元组传递给 gg
而不是传递非 const 引用元组(std::tie
使)。这可以通过以下方式完成:
gg( std::tie( std::cref(x) ) );
然而,对 std::cref
的额外调用有点乏味,所以最好有像 ctie
这样的东西,它会生成一个 const 引用的元组.
第二个问题是是否需要手动编写ctie
,如果是,那么这是最好的方法吗?
template < typename... T >
std::tuple<const T&...> ctie( const T&... args )
{
return std::tie( args... );
}
最佳答案
The first question is if this fits with the C++11 standard, and if it doesn't, then why?
这是预期的行为。在第二种情况下,模板参数推导失败,因为没有 T
这样tuple<const T&>
变成 tuple<int&>
.
在第一种情况下它有效,因为 tuple<int&>
可隐式转换为 tuple<const int&>
.这是用户定义的转换,因此在模板参数推导过程中不考虑。
你的问题有点像 X/Y 问题。考虑发布 real 问题,让您寻找涉及这种函数模板/元组组合的解决方案。
您的ctie
功能模板看起来不错。但请记住,像
auto t = ctie(5);
基本上会产生一个悬空引用。所以,您可能想要限制 ctie
仅限左值。
关于c++ - 如何制作一个 const 引用的元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18213374/