Jar*_*ock 13 c++ templates parameter-passing c++11
我需要一个类型特征,它将根据仿函数的operator()类型和传递给它的参数类型报告仿函数参数的类型.基本上,我需要准确确定将参数传递给仿函数时转换为什么类型.为简单起见,我们假设我只对operator()一个参数感兴趣(可能模板化,可能过载).不幸的是,我只限于c ++ 03.可以吗?如果没有,那么c ++ 11怎么样?
这是一个例子:
#include <cassert>
#include <type_traits>
template<typename Functor, typename Argument>
struct parameter_type
{
// what goes here?
typedef ... type;
};
struct takes_float_cref
{
void operator()(const float &);
};
int main()
{
// when calling takes_float_cref::operator() with an int,
// i'd expect a conversion to const float &
assert(std::is_same(parameter_type<takes_float_cref, int>::type, const float &>::value);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
首先,我会这样做:
template<typename F>
struct parameter_type_impl;
// may be with variadic arguments
template<typename R, typename A, typename F>
struct parameter_type_impl<R (F::*)(A)> {
typedef A type;
};
template<typename F>
struct parameter_type {
typedef typename parameter_type_impl<decltype(&F::operator())>::type type;
};
Run Code Online (Sandbox Code Playgroud)
我不明白你为什么要传递实际的参数类型。如果转换无法发生,您必须稍后使用特殊措施(例如 SFINAE)。我认为这两件事是正交的:推导参数类型,然后决定您想要传入的参数是否可转换。
非 C++03 decltype 很难摆脱。指定函数类型始终需要了解参数。一旦你阐明了论点,整件事就变得毫无意义了。
同样的问题也会发生在Boost.Function Types.
| 归档时间: |
|
| 查看次数: |
495 次 |
| 最近记录: |