首页 文章

调用模板函数,模板指针指向函数[关闭]

提问于
浏览
0

我的问题是我尝试调用我的模板函数test,它将指针指向另一个模板函数 . 因为你不能有模板指向函数,我通过在struct中包装这样的typedef指针来实现它(参见Template typedefs - What's your work around?) . 它's OK - I can call my template function by a pointer, but problem is that I can' t调用将该指针作为参数的函数 . VS2010中的错误是:

c:\ projects \ sort \ sort \ sort.cpp(114):错误C2059:语法错误:'}'c:\ projects \ sort \ sort \ sort.cpp(124):参见函数模板实例化'void test (void(__ cdecl *)(std :: vector <_Ty>&))'用[_Ty = int]编译

Build 失败 .

_Ty是int,没关系,对吗?

#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
    //...
 }

1 回答

  • 2

    这一行是问题所在:

    while(i<0xFF)do{
    

    正确的语法是

    while(i<0xFF){
    

    .

相关问题