在这个虚构的例子,我想一个函数模板传递给我的功能,并希望我的函数实例化函数模板内部。实质上,我不希望用户知道我的函数的类型和工作方式,但只需要通过函数模板就可以实例化我自己。自包含的例子(不编译):延迟功能模板实例
#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 –