Passing a function as an argument to a class template

Not knowing the type of function, I declare its pointer below using the method and initializing the function pointer.

template<typename T>
struct Declare { typedef T Type; }; // for declaring any func ptr

void fun () {}

int main ()
{
  Declare<fun>::Type pf = &fun;  // can't use C++0x 'auto'
}

However, it gives compiler error as error: expected a type, got ‘fun’. Although the type of any method is known at compile time. Is it invalid to pass a function to a class templateas described above?

[Note: replacing funwith void (*)()works fine. But this is not what is needed.]

+5
source share
2 answers

Is it not valid to pass a function to a class template as described above?

. , , , , ++. , fun , void (*)(). , . .

, . , , :

Declare obj(&fun); 

, , , . , , : , , AbstractFunctor (, ) , template<Fun fun> struct Functor. Functor, , AbstractFunctor* Declare.

, Declare::Type Declare::AbstractFunctor::Type, , ; . , A::Type . , instance.Type. , , : , , .


EDIT:

++ 0x ( ), :

Declare<decltype(&fun)>::Type pf = &fun;  
pf(); //call the function

: http://ideone.com/

Declare, :

decltype(&fun) pf = &fun; 
pf(); //call the function   
+3

, ?

, -.
fun -, , , 0x12345678.
typename T - . , int, MyClass, double (*)(std::string), void (MyClass::*)().
, - , .
, Boost.Typeof -++ 0x-, . auto BOOST_AUTO, BOOST_TYPEOF:

int hello(){ return 42; }
BOOST_AUTO(var1,hello()); // type of var1 == int
BOOST_TYPEOF(hello()) var2 = hello(); // same

? , . . Ideone.


, , Boost.Typeof. ? , , , , , ? ?
. , auto fptr = &func, , func , . , func , , , :

template<class FPtr>
void myfunc(FPtr otherfunc){
  // use otherfunc
}

.

+5

All Articles