【问题标题】:call to template function which takes template pointer to function [closed]调用模板函数,该函数将模板指针指向函数[关闭]
【发布时间】:2013-01-27 11:53:14
【问题描述】:

我的问题是我尝试调用我的模板函数测试,它需要指向另一个模板函数的指针。因为你不能有指向函数的模板化指针,所以我通过将这样的 typedef 指针包装在结构中来做到这一点(参见Template typedefs - What's your work around?)。没关系 - 我可以通过指针调用我的模板函数,但问题是我不能调用以这个指针作为参数的函数。 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 ]

构建失败。

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

【问题讨论】:

  • std::function 有什么问题?
  • 我认为 std::function 没有错,但我的问题是如何调用这个模板 func 测试,因为我认为有可能我想知道

标签: c++ templates pointers typename


【解决方案1】:

这行是问题所在:

while(i<0xFF)do{

正确的语法是

while(i<0xFF){

.

【讨论】:

  • 显然。实际上问题之一,我已经改变了这一点,现在问题是计时器:sortTime中的“在表达式中非法使用命名空间标识符”。谢谢,我更近了
  • 但我会解决不同的问题。谢谢。顺便说一句:编译器没有捕捉到这个愚蠢的遗漏,他抱怨缺少“}”,但我只是完全专注于模板; p
  • @cf16: boost::timer 是一个命名空间,试试boost::timer::cpu_timer
  • 是的,它有效。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多