c++ - 调用将模板指针指向函数的模板函数

标签 c++ templates pointers typename

<分区>

我的问题是我尝试调用我的模板函数测试,它接受指向另一个模板函数的指针。因为你不能有指向函数的模板化指针,所以我通过在结构中包装这样的 typedef 指针来做到这一点(参见 Template typedefs - What's your work around? )。没关系——我可以通过一个指针调用我的模板函数,但问题是我不能调用以这个指针作为参数的函数。 VS2010 中的错误是:

c:\projects\sort\sort\sort.cpp(114): error C2059: 语法错误:'}' c:\projects\sort\sort\sort.cpp(124) :参见正在编译的函数模板实例化'void test(void (__cdecl *)(std::vector<_Ty> &))' 和 [ _Ty=整数 ]

构建失败。

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

最佳答案

这一行是问题所在:

while(i<0xFF)do{

正确的语法是

while(i<0xFF){

.

关于c++ - 调用将模板指针指向函数的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14547053/

相关文章:

c++ - aspect c++ 跟踪函数控制流和输入输出参数

带有静态指针的 C++ 类

c++ - 在 C Linux 中使用三个线程使用信号量同步按顺序打印 3 4 5 50 次

用于实时音频合成的 C++ 精确 44100Hz 时钟

C++ STL 访问 vector 元素

php - 如何在模块中使用 ExpressionEngine 表单验证类来重新填充模板中的表单?

c++ - 具有递归继承和使用声明的可变参数模板

c++ - boost 图形库 : Bundled Properties and iterating across edges

c - 在C中,如何对每个指针都指向可变长度int数组的指针数组进行排序?

java - 指针和垃圾收集