gpt4 book ai didi

c++ - 函数参数的类型是否可推导?

转载 作者:可可西里 更新时间:2023-11-01 18:29:06 27 4
gpt4 key购买 nike

我有一个使用返回码的类:

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);

参见 related question了解更多详情。

关于c++ - 函数参数的类型是否可推导?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44951873/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com