c++ - 如何制作一个 const 引用的元组?

标签 c++ c++11 gcc tuples tie

说有两个功能:

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/

相关文章:

c++ - 使用 const 引用删除引用

c++ - 我如何从 C++ 中的静态线程入口点函数调用其他函数?

c++ - 创建的文件中的文件 I/O

c++ - Travis CI 与 Clang 3.4 和 C++11

只能隐式构造的C++11类?

c++ - 为什么空数组的大小为 0 而空类的大小不为 0?

在不同的系统上编译相同的程序会产生不同的结果吗?

c++ - 将 GCC/ATT 风格的汇编程序转换为 visual studio 汇编程序?

c++ - 如何创建一组可以循环访问的 UI 元素

signals - signal.h中的Siginfo结构已更改-如何容纳?