我很难搞定这件简单的事情。
我发现有一件事是有效的:
#include <type_traits>
struct A
{
int Method();
};
static_assert( std::is_same_v<
decltype(A{}.Method()), int
>
); // pass. cool.
太好了。但不是;不是很好。因为我现在有一个默认的可构造要求,我需要用所有参数编写一个调用表达式。谁知道他们!
考虑一下真实情况:
struct A
{
int Method(MysteriousArgumentsIDontCareAboutAndCanChangeInTheFuture);
};
static_assert( std::is_same_v<
decltype(A{}.Method()), int
>
); // not so cool anymore (too few arguments to function call, expected 1, have 0)
使用std::invoke_result
怎么样?
static_assert( std::is_same_v<
std::invoke_result_t< A::Method >, int
>
);
罗。
在没有object参数的情况下调用非静态成员函数
MSVC说
非标准语法;使用'&'创建指向成员的指针
我可以用这个表达来捣乱我所想要的一切,没有任何好处。 例如。:
using T = std::invoke_result_t< decltype(&A::Method) >;
错误:'std :: invoke_result中没有名为'type'的类型
如果我删除decltype
它的类型 - 值不匹配(当然)等...
cppreference.com提到了C ++ 14版本的这种用法:
std::result_of<decltype(&C::Func)(C, char, int&)>::type
没有比我的第一次尝试好多少。所有论点仍然存在。 在我们的简单案例中:https://godbolt.org/z/KtQbth
救命 ?
您可以使用Piotr Skotnicki建议的特征:
template <typename T>
struct return_type;
template <typename R, typename... Args>
struct return_type<R(Args...)> { using type = R; };
template <typename R, typename... Args>
struct return_type<R(*)(Args...)> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...)> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) &> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) &&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const&&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) volatile> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) volatile&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) volatile&&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const volatile> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const volatile&> { using type = R; };
template <typename R, typename C, typename... Args>
struct return_type<R(C::*)(Args...) const volatile&&> { using type = R; };
template <typename T>
using return_type_t = typename return_type<T>::type;
现在你可以这样做:
static_assert(std::is_same_v<return_type_t<decltype(&A::Method)>, int>);
[static_assert( std::is_same_v< decltype(std::declval<A>().Method()), int >);//super cool now][1]