成员函数参数的类型

问题描述 投票:3回答:1

使用C ++ 11我试图从函数名中获取函数参数的类型,授予函数签名是明确的。最后,我试图在调用函数之前检查参数是否是我想要的类型。

到目前为止,由于这个解决方案,我可以使用非成员函数来实现:Unpacking arguments of a functional parameter to a C++ template class

我稍微编辑了它以获得以下类:

template<typename T>
struct FunctionSignatureParser; // unimplemented primary template
template<typename Result, typename...Args>
struct FunctionSignatureParser<Result(Args...)>
{
    using return_type = Result;
    using args_tuple = std::tuple<Args...>;
    template <size_t i> struct arg
    {
        typedef typename std::tuple_element<i, args_tuple>::type type;
    };
};

例如,我可以在编译时检查函数的类型:

short square(char x) { // 8-bit integer as input, 16-bit integer as output
    return short(x)*short(x);
}
int main() {
        char answer = 42;
        static_assert(std::is_same<char, FunctionSignatureParser<decltype(square)>::arg<0>::type>::value, "Function 'square' does not use an argument of type 'char'");
        static_assert(std::is_same<short, FunctionSignatureParser<decltype(square)>::return_type>::value, "Function 'square' does not return a value of type 'short'");
        short sqrAnswer = square(answer);
        std::cout << "The square of " << +answer << " is " << +sqrAnswer << std::endl;
        return 0;
}

>> Online code with gcc

但是当我想检查成员函数的类型时,一些编译器对它不满意:

struct Temperature
{
    double degrees;
    Temperature add(double value);
};
int main() {
    Temperature t{16};
    double increment{8};
    static_assert(std::is_same<double, FunctionSignatureParser<decltype(t.add)>::arg<0>::type>::value, "Method 'Temperature::add' does not use an argument of type 'double'");
    std::cout << t.degrees << u8" \u00b0C + " << increment << " == " << t.add(increment).degrees << u8" \u00b0C" << std::endl;
    return 0;
}

这是gcc 6.3必须说的:

错误:无效使用非静态成员函数'Temperature Temperature :: add(double)'

>> Online code with gcc

这是clang 4.0必须说的:

错误:必须调用对非静态成员函数的引用

>> Online code with clang

我尝试过这些选项,但无济于事:

decltype(Temperature::add)
decltype(std::declval<Temperature>().add)

decltype中的非静态成员函数有什么问题?由于没有评估decltype中的表达式,所以static限定符应该不重要,对吗?

为了记录,MSVC12在这种情况下取​​得了成功。但我无法判断Microsoft编译器是对还是错。 (请不要让这个线程成为编译器之战)

此外,如果你有一个不涉及初始方法的参数检查解决方案,我也是开放的。

c++ c++11 gcc decltype member-functions
1个回答
3
投票

您需要另一个模板专门化的成员函数,如下所示:

template<typename ClassType, typename Result, typename...Args>
struct FunctionSignatureParser<Result(ClassType::*)(Args...)>
{
    using return_type = Result;
    using args_tuple = std::tuple<Args...>;
    template <size_t i> struct arg
    {
        typedef typename std::tuple_element<i, args_tuple>::type type;
    };
};

它可以像这样使用:

    static_assert(std::is_same<double, FunctionSignatureParser<decltype(&Temperature::add)>::arg<0>::type>::value, "Method 'Temperature::add' does not use an argument of type 'double'");

这适用于gcc 7.2,尚未测试过其他编译器

© www.soinside.com 2019 - 2024. All rights reserved.