简体   繁体   English

使用decltype声明整个函数类型本身(不是指针!)

[英]Using decltype to declare the entire function type itself (not pointer!)

So I have a function with a specific signature in a header file, and I want to declare another function with the exact same signature inside a class without typing the parameters again, and of course, hopefully without a macro... The member function should also have an extra hidden parameter obviously, the this pointer (since it's not a static member function). 所以我在头文件中有一个具有特定签名的函数,我想在类中声明另一个具有完全相同签名的函数, 而无需再次输入参数,当然,希望没有宏...成员函数应该显然还有一个额外的隐藏参数, this指针(因为它不是静态成员函数)。

Now, I'm actually surprised that the following hack/trick works in both GCC and ICC, but I'm not sure if it's "legal" C++. 现在,我确实惊讶的是,下面的技巧/诀窍在GCC和ICC 的作品 ,但我不知道这是否是“合法”的C ++。 I'm not particularly concerned with legality if it's a supported extension , but unfortunately I do not want it to break on a compiler version update because some people decided to arbitrarily block this useful feature since the standard says "no" (that kind of stuff really annoys me to be honest). 我不是特别关注合法性, 如果它是一个支持的扩展 ,但不幸的是我不希望它打破编译器版本更新,因为有些人决定任意阻止这个有用的功能,因为标准说“不”(那种东西说实话真让我烦恼。

Here's what I mean: 这就是我的意思:

// test.hpp
int func(int x) { return x; }

struct foo
{
  decltype(func) fn;  // <-- legal?
};

int test()
{
  return foo().fn(6);
}


// then in test.cpp
int foo::fn(int x) { return x + 42; }

This works (with GCC and ICC), but I don't know if it's "legal" in the standard. 有效 (与GCC和ICC),但我不知道它是否在标准中是“合法的”。 I'm asking just to be assured that it is legal and it won't suddenly stop working in the future. 我要求确保它是合法的,它不会在将来突然停止工作。

(if it's not legal and you want to report it as a bug, please mark it as a suggestion to make it a legal compiler extension instead of killing it...) (如果它不合法并且您想将其报告为错误,请将其标记为建议,使其成为合法的编译器扩展而不是将其删除......)

Basically, it's the same as declaring int fn(int x); 基本上,它与声明int fn(int x); in the struct, and that's how it works currently. 在结构中,这就是它当前的工作方式。

If you ask me for a use case: it's to declare a wrapper member function for the other free function which does something with the this pointer before passing it to the free function. 如果你问我一个用例:它是为另一个自由函数声明一个包装器成员函数,它在将它传递给free函数之前用this指针做了一些事情。 Its parameters must match exactly, obviously. 显然,它的参数必须完全匹配。 Again, I don't want to type the parameters again. 同样,我不想再次输入参数。

That looks legal; 这看似合法; but at definition you have to retype. 但根据定义,你必须重新输入。 Consider using perfect forwarding instead. 考虑使用完美转发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM