使用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;
}但是,当我想检查成员函数的类型时,一些编译器对此并不满意:
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要说的是:
错误:无效使用非静态成员函数“温度::加法(双)”
以下是clang 4.0必须说的话:
错误:必须调用对非静态成员函数的引用。
我尝试了这些选择,但没有结果:
decltype(Temperature::add)
decltype(std::declval<Temperature>().add)decltype中的非静态成员函数有什么问题?由于没有计算decltype中的表达式,所以static限定符应该无关紧要,对吗?
为了记录在案,MSVC12在这种情况下成功了。不过,我不知道Microsoft编译器是对是错。(请不要让这个线程成为编译器的战争)
另外,如果您有一个不涉及初始方法的参数检查的解决方案,我也愿意接受它。
发布于 2017-12-20 13:00:43
您需要对成员函数进行另一个模板专门化,如下所示:
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,还没有测试过其他编译器
https://stackoverflow.com/questions/47906426
复制相似问题