C ++ 11:函数模板返回任意类型的{2}容器

时间:2017-04-23 14:09:10

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

我试图解决大学问题,除其他外,要求我们编写一个带有参数的函数: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 {    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);
    ^
};
    foo(v);
}

它会抛出错误:

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

我对C ++类型知之甚少,所以我真的不明白是什么类型&#34;推论&#34;这里。我们对decltype和函数模板的介绍很少,而且我们所涵盖的任何其他内容都无法解决。我们不允许在我们的课程之外使用这么多(仅限C ++ 11),所以我认为我或者在某处或那里犯了一个菜鸟错误,这是一种更优雅的方式。< / p>

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

MediaRecorder mediaRecorder;
mediaRecorder = new MediaRecorder();
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
//mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setOutputFile(videoFilename);
mediaRecorder.setVideoEncodingBitRate(1000000);
mediaRecorder.setVideoFrameRate(30);
mediaRecorder.setVideoSize(videoSize.getWidth(), videoSize.getHeight());
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
//mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
try {
    mediaRecorder.prepare();
} catch (IOException e) {
    e.printStackTrace();
}

1 个答案:

答案 0 :(得分:0)

remove_reference<decltype(bar)>未删除decltype(bar)中的引用 - 您需要

typename remove_reference<decltype(bar)>::type

阅读remove_reference documentation

相关问题