2013-01-02 59 views
3

在這個虛構的例子,我想一個函數模板傳遞給我的功能,並希望我的函數實例化函數模板內部。實質上,我不希望用戶知道我的函數的類型和工作方式,但只需要通過函數模板就可以實例化我自己。自包含的例子(不編譯):延遲功能模板實例

#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’ 

是否有任何技巧或間接引用一個可以拉動以解決這個問題?

謝謝。

回答

2

只是爲了完整性,這裏的仿函數方法的一個例子:

#include <algorithm> 
#include <vector> 
#include <iostream> 

struct Copy { 
    template <typename InputIter, typename OutputIter> 
    OutputIter operator()(InputIter i1, InputIter i2, OutputIter o1) { 
    return std::copy(i1, i2, o1); 
    } 
}; 

template <typename CopyFunctor> 
void foo(CopyFunctor cf) { 
    std::vector<int> v1 = {3, 1, 4}; 
    std::vector<int> v2(v1.size()); 

    cf(v1.begin(), v1.end(), v2.begin()); 

    for (auto i : v2) { 
    std::cout << i << ' '; 
    } 
} 

int main() { 
    foo(Copy()); // displays "3 1 4" 
} 
0

將東西沿線

template <template <typename InputIt, typename OutputIt> class CopyFunc> void transferWith() 
{ 
    std::vector<int> source{1, 2, 3, 4, 5, 6, 7}; 
    std::vector<int> sink; 

    CopyFunc<std::vector<int>::const_iterator, std::vector<int>::iterator>(source.begin(), source.end(), std::back_inserter(sink)); 

    for (auto&& e : sink) 
    { 
     std::cout << e << std::endl; 
    } 
} 

稱爲:

transferWith<std::copy>(); 

嗎?

我不看好這會編出一箱......

2

是否有任何技巧或間接引用一個可以拉動來解決這個問題?

是的。使用模板operator()()傳遞函子對象。

該代碼看起來與Bart's answer中的版本完全相同。

+0

有趣。所以看起來你不能傳遞一個沒有實際意義的函數模板作爲模板模板參數。你只能通過類模板來做到這一點,因此我們需要將它作爲一個函數對象。以下是可用的代碼:http://liveworkspace.org/code/2ww7xE$8 –