【问题标题】:Is it possible to use typedef in a templated function signature?是否可以在模板函数签名中使用 typedef?
【发布时间】:2011-11-14 18:46:45
【问题描述】:
有没有办法使用 typedef 作为模板函数的参数?还是一种将类型定义为参数的方法?
假设我想将一个函数指针传递给这个函数:
template<typename C, typename ...Args>
void test(typedef void (C::*functor)(Args... args) functor f)
{
f(args...);
}
【问题讨论】:
标签:
c++
templates
c++11
typedef
【解决方案1】:
不,您不能在参数中创建typedef。如果你的目标是避免在函数体中重复参数的类型,你可以使用decltype:
template<typename C, typename ...Args>
void test(void (C::*f)(Args...))
{
typedef decltype(f) functor;
}
【解决方案2】:
没有。
但是当你可以写这个时,你为什么还要这样:
template<typename C, typename ...Args>
void test(void (C::*f)(Args...), Args... args)
{
C c; //f is a member function, so need an instance of class
(c.*f)(args...); //call the function using the instance.
}
或者,您可以将实例与参数一起传递,或者执行其他操作。我认为这只是一个概念验证,在实际代码中会是别的东西。