函数参数的类型是否可以推导?
Is the type of a function parameter deducible?
我有一个使用返回码的类:
class MyClass
{
// ...
public:
// ValueType get_value() const; // usual code
ErrorCode get_value(ValueType& value) const; // uses error code
// ...
};
因此,get_value()
的第二种形式实际上将值作为函数参数提供,而不是作为返回值。
是否可以推导出get_value()
函数参数的类型,也许使用decltype
?
int main()
{
// ...
MyClass my_class;
// auto val = my_class.get_value(); // okay: value has correct type
declytype( /* something here */ ) value;
const auto error = my_class.get_value( value );
// ...
}
如果要推断参数的类型,可以使用模板来执行此操作:
namespace detail
{
template<typename>
struct Helper;
template<typename R, typename C, typename T>
struct Helper <R(C::*)(T)>
{
using type = T;
};
}
然后像这样使用它:
detail::Helper<decltype(&MyClass::get_value)>::type value;
// ...
const auto error = my_class.get_value(value);
有关更多详细信息,请参阅相关问题。
一种更紧凑的解决方案,不需要完全定义新类型。
您可以使用函数声明(无需定义(并decltype
来执行此操作。
它遵循一个最小的工作示例:
#include<type_traits>
template<typename R, typename C, typename T>
constexpr T f(R(C::*)(T));
struct S {
void f(int) {}
};
int main() {
static_assert(std::is_same<int, decltype(f(&S::f))>::value, "!");
}
您还可以通过使用元组轻松地将其扩展到多个参数:
template<typename R, typename C, typename... T>
constexpr std::tuple<T...> f(R(C::*)(T...));
在 C++17 中,您还可以使用模板参数获得更加用户友好的类型处理程序auto
:
template<auto M>
using Type = decltype(f(M));
并将其用作:
static_assert(std::is_same_v<int, Type<&S::f>>);
相关文章:
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 是否可以对零模板参数进行模板专门化
- 函数作为模板参数,是否对返回类型强制约束
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 函数是否可以访问传递给main()的参数
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 如何检查给定的参数是否为 cv::noArray()?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 如果返回 -1,时间() 的参数是否被修改?
- 用于检查值是否为其任何参数的帮助程序函数
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 模板化检查是否存在带有参数列表的类成员函数?
- 我如何知道作为参数的size_t在函数中是否有效?
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 是否可以在运行时强制转换模板参数?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 编译器是否强制根据模板参数计算表达式?
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?