【问题标题】:C++11: Function template returning 2D containers of arbitrary typesC++11:返回任意类型的二维容器的函数模板
【发布时间】:2017-04-23 14:09:10
【问题描述】:

我正在尝试解决一个大学问题,除其他外,它要求我们编写一个带有参数的函数:Type1 的容器,其中包含 Type2 的容器,其中包含 Type3 的容器,其中包含以下元素任意类型。容器类型不必不同,但已知的是它们仅支持少数函数(例如 size()),并且所有维度都相同。到目前为止,我们只处理了序列容器,所以我认为他们将使用自定义序列容器进行测试。

我需要的是一个返回包含 Type1 容器的 Type2 容器的函数。我尝试使用这样的结构:

template <typename Cube>
    auto foo(const Cube &bar) -> remove_reference<decltype(bar)>
    {
        auto square(remove_reference<decltype(bar)> {});
        cout << square.size(); // Throws an error
        return square;
    }

希望 decltype 能帮助我制作一个包含 Type1 容器的 Type2 容器。但是,当我使用 3D 矢量作为参数调用函数时:

int main() {
    vector<vector<vector<int>>> v {{{1}}};
    foo(v);
}

它会抛出一个错误:

    error: no member named 'size' in 'std::remove_reference<const std::vector<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >, std::allocator<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > > > &>'
                cout << square.size();
                        ~~~~~~ ^  
note: in instantiation of function template specialization 'foo<std::vector<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >, std::allocator<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > > > >' requested here
    foo(v);
    ^

我对 C++ 类型知之甚少,所以我不太明白这里“推导”了什么类型。关于 decltype 和函数模板,我们涉及的内容很少,而且我们所涉及的任何其他内容都没有帮助浮现在脑海中。我们不允许在课程之外使用太多内容(仅限 C++11),所以我认为要么我在某个地方犯了一个新手错误,要么有更优雅的方法来做到这一点。

编辑:返回值和平方应该被指定为

auto square(remove_reference<decltype(bar[0])> {});

【问题讨论】:

    标签: c++11 containers decltype function-templates


    【解决方案1】:

    remove_reference&lt;decltype(bar)&gt; 没有从 decltype(bar) 中删除引用 - 你需要

    typename remove_reference<decltype(bar)>::type
    

    阅读remove_reference documentation

    【讨论】:

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