成员函数参数的类型

时间:2017-12-20 12:46:49

标签: c++ c++11 gcc decltype member-functions

使用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编译器是对还是错。 (请不要让这个线程成为编译器之战)

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

1 个答案:

答案 0 :(得分: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,尚未测试其他编译器