Pergunta

my problem is I try to call my template function test which takes pointer to another template function. since you can't have templated pointer to function I did it by wrapping such typedef pointer in struct (see Template typedefs - What's your work around?). it's OK - I can call my template function by a pointer, but problem is that I can't call function that takes this pointer as argument. error in VS2010 is:

c:\projects\sort\sort\sort.cpp(114): error C2059: syntax error : '}' c:\projects\sort\sort\sort.cpp(124) : see reference to function template instantiation 'void test(void (__cdecl *)(std::vector<_Ty> &))' being compiled with [ _Ty=int ]

Build FAILED.

_Ty is int, and it is OK, right?

#include "stdafx.h"
#include <vector>
#include <iterator>//for ostream_iterator
#include <algorithm>//for copy
#include <iostream>//for cout
#include <map>
#include <boost/timer/timer.hpp>
#include <boost/random.hpp>
#include <functional>

template <typename T>
void insert_sort(typename std::vector<T>& v){ // O(n^2)
    for(std::vector<T>::iterator it=v.begin();it!=v.end();it++){
        std::vector<T>::iterator it2=it; // [0,...,i-1] has been sorted already
        T temp = *it2;
        while(it2!=v.begin() && *(it2-1)>temp){
            *(it2)=*(it2-1);
            it2--;
        }
        *(it2)=temp;
    }
}
void f(int i){std::cout<<i<<" ";}

template<typename T>
struct sort_struct{
    typedef void (*func_sort)(std::vector<T>& );
    typedef std::map<int,T> mymap;
};

template<typename T>
double sortTime(std::vector<T>& v, typename sort_struct<T>::func_sort f){
    boost::timer t; // start timing
    f(v);
    return t.elapsed();
}

template<typename T>
void test(typename sort_struct<T>::func_sort f){
    int i=100;
    while(i<0xFF){
        boost::mt19937 marsenneTwister;
        boost::uniform_int<> unigen;
        boost::variate_generator<boost::mt19937, boost::uniform_int<> > 
            gen(marsenneTwister, unigen);
        std::vector<int> randVec(i);
        std::random_shuffle(randVec.begin(), randVec.end(), gen);
        double elapsed = sortTime(randVec,f);
        std::cout<<i<<","<<elapsed<<std::endl;
            i+=100;
    }
}


int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<int> vi(2);
    sort_struct<int>::func_sort isort_int=insert_sort<int>;
    (*isort_int)(vi); // this is OK

    // how to instantiate and call test<int> ?
    test<int>(isort_int); // error
    //...
 }
Foi útil?

Solução

This line is the problem:

while(i<0xFF)do{

The correct syntax is

while(i<0xFF){

.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top