我已经看到此页面的一些代码片段 https://en.cppreference.com/w/cpp/types/result_of并注意到这个特定的函数模板签名类型:
template<class F, class... Args>
static auto call(F&& f, Args&&... args)
-> decltype(std::forward<F>(f)(std::forward<Args>(args)...));
注意:从给定的实现来看,根本没有定义,仅指定其返回类型。
如果这是可能的,有哪些可能的应用程序可以用于此目的?
最佳答案
是的,这是允许的。 decltype 是一个未计算的上下文,因此该函数实际上并未被调用,仅确定了它的返回类型。拿std::declval
例如。它是标准声明的函数模板,仅允许在未计算的表达式中使用,因为它可能没有定义。
我喜欢将这些类型的函数称为元函数。您可以像类型特征一样使用它们,或者作为帮助者来构建模板代码的类型。前几天我在一个答案中使用了一个,它用于帮助将一种类型的元组转换为另一种类型。看起来像
template <template <typename> typename Transformer, typename... Ts>
auto transform_types(std::tuple<Ts...>) -> std::tuple<typename Transformer<Ts>::type...>;
我用它来构建一个类似的类型
template <template <typename> typename Transformer, typename Tuple>
using transform_types_t = decltype(transform_types<Transformer>(std::declval<Tuple>()));
如果您想查看完整示例,请点击该帖子的链接:Transform the std::tuple types to another ones
关于c++ - 使用没有定义的函数c++合法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68668285/