Dan*_*ger 30 c++ decltype c++11
特定
struct A {
int foo(double a, std::string& b) const;
};
Run Code Online (Sandbox Code Playgroud)
我可以像这样创建一个成员函数指针:
typedef int (A::*PFN_FOO)(double, std::string&) const;
Run Code Online (Sandbox Code Playgroud)
很容易,但PFN_FOO
如果A::foo
签名发生变化则需要更新.自C++ 11引入以来decltype
,它是否可以用于自动推导签名并创建typedef?
Mat*_* M. 19
一个问题:如果此变量是明确的,您可能只推导出变量的类型.
函数的主要问题是重载意味着它们的名称不足以识别它们.因此,如果使用decltype
失败,你应该引入foo
in 的重载A
.
struct A {
void foo() const;
void foo(int) const;
};
using PFN_FOO = decltype(A::foo);
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)source.cpp:6:36: error: decltype cannot resolve address of overloaded function
不确定你会获得多少......
另一方面,您实际上可以使用别名并检查别名是否正确:
struct A {
void foo() const;
void foo(int) const;
};
using PFN_FOO = void (A::*)(int) const;
static_assert(std::is_same<PFN_FOO, decltype(static_cast<PFN_FOO>(&A::foo))>::value,
"Ooops, need to update signature of PFN_FOO!");
Run Code Online (Sandbox Code Playgroud)
注意:不确定这是最好的测试方法,基本上你需要的只是static_cast
部分,我只想隐藏一条错误信息.你可能需要像SFINAE这样的东西来获得更好的信息.