在這個虛構的例子,我想一個函數模板傳遞給我的功能,並希望我的函數實例化函數模板內部。實質上,我不希望用戶知道我的函數的類型和工作方式,但只需要通過函數模板就可以實例化我自己。自包含的例子(不編譯):延遲功能模板實例
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
template <template <typename InputIt, typename OutputIt> class CopyFunc>
void transferWith(CopyFunc<std::vector<int>::const_iterator,
std::back_insert_iterator<std::vector<int>>> const& func)
{
std::vector<int> source{1, 2, 3, 4, 5, 6, 7};
std::vector<int> sink;
func(source.begin(), source.end(), std::back_inserter(sink));
for (auto&& e : sink)
{
std::cout << e << std::endl;
}
}
int main(int argc, char const *argv[])
{
// I want to pass just the function template in,
// and instantiate it internally
transferWith(std::copy);
return 0;
}
這未能在GCC-4.7.2編譯如預期,併產生以下錯誤:
main.cpp|25 col 27 error| no matching function for call to ‘transferWith(<unresolved overloaded function type>)’
main.cpp|8 col 6 error| note: template<template<class InputIt, class OutputIt> class CopyFunc> void transferWith(const CopyFunc<__gnu_cxx::__normal_iterator<const int*, std::vector<int> >, std::back_insert_iterator<std::vector<int> > >&)
main.cpp|25 col 27 error| note: couldn't deduce template parameter ‘template<class InputIt, class OutputIt> class CopyFunc’
是否有任何技巧或間接引用一個可以拉動以解決這個問題?
謝謝。
有趣。所以看起來你不能傳遞一個沒有實際意義的函數模板作爲模板模板參數。你只能通過類模板來做到這一點,因此我們需要將它作爲一個函數對象。以下是可用的代碼:http://liveworkspace.org/code/2ww7xE$8 –