函数参数的类型是否可推导?
Is the type of a function parameter deducible?
我有一个 class,它使用 return 代码:
class MyClass
{
// ...
public:
// ValueType get_value() const; // usual code
ErrorCode get_value(ValueType& value) const; // uses error code
// ...
};
因此,get_value()
的第二种形式实际上提供了作为函数参数的值,而不是作为 return 值。
是否可以推断出 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。
不需要完全定义新类型的更紧凑的解决方案。
您可以使用函数声明(无需定义)和 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>>);
我有一个 class,它使用 return 代码:
class MyClass
{
// ...
public:
// ValueType get_value() const; // usual code
ErrorCode get_value(ValueType& value) const; // uses error code
// ...
};
因此,get_value()
的第二种形式实际上提供了作为函数参数的值,而不是作为 return 值。
是否可以推断出 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。
不需要完全定义新类型的更紧凑的解决方案。
您可以使用函数声明(无需定义)和 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>>);