c++ - 如何使用 C++ 中的类型特征获取函数参数的类型?

标签 c++ templates

<分区>

我有这个功能:

template <typename F>
void doSomethingWith(F func) {

   T obj = getObjectFromSomewhereElse<T>();
   func(obj);
}

我想推导出类型 T来自 F , 其中TF 的第一个(在本例中是唯一的)参数.有没有办法在 C++ 中执行此操作?

最佳答案

对于一个参数,这是一种简单的方法:

template<typename> struct arg;

template<typename R, typename A>
struct arg<R(*)(A)> { using type = A; };

用作 ( live example )

template<typename T>
T getObjectFromSomewhereElse() { return T{}; }

template <typename F>
void doSomethingWith(F func)
{
    using T = typename arg<F>::type;
    T obj = getObjectFromSomewhereElse<T>();
    func(obj);
}

void f(int x) { std::cout << x << std::endl; }

int main ()
{
    doSomethingWith(f);  // output 0
}

这里我们知道 func 会衰减为一个指针,这就是为什么我们为指向函数的指针定义 arg 的原因。

这只适用于函数。对于函数对象(和 lambda),我们需要使用指向成员 operator() 的指针,如 here 所示。 (感谢 Jarod42)和 here (感谢 OmnipotentEntity)。

关于c++ - 如何使用 C++ 中的类型特征获取函数参数的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23112016/

相关文章:

c++ - 在 Visual Studio Code 中编译 C++ 代码

c++ - 使用 SDL 时出现段错误

c++ - 使用推导类类型的占位符指定类型的非类型模板参数是否可以传递给 C++2a 中的另一个模板?

c++ - 如何将标准例程添加到函数指针数组中的每个函数?

c++ - VS 2012 模板错误

c++ - 如何在 C++ 模板声明中声明函数

c++ - 意外的 std::io_base::failure 异常

c++ - 将整个二进制文件读入缓冲区,然后以特定格式解析它

c++ - 复制构造函数中 const_cast 的含义?

c++ - 模板化检查是否存在类成员函数?