我有这个代码:
struct Test {
std::string s;
};
template <typename T,
auto T::* groupPtr>
struct Base{
using BaseType = typename std::decay<decltype(std::declval<T>().*groupPtr)>::type;
void Process(const Test * e){
printf("%s\n", e->s.c_str());
BaseType tmp = e->*groupPtr;
printf("%s\n", tmp.c_str());
}
};
int main(){
Test t;
t.s = "x";
Base<Test, &Test::s> r;
r.Process(&t);
}
但是,编译以错误结束:main.cpp: error C2440: 'specialization': cannot convert from
'std::string Test::* ' to 'auto Test::* '
main.cpp: message : Types pointed to are unrelated; conversion
requires reinterpret_cast, C-style cast or function-style cast
main.cpp: error C3535: cannot deduce type for 'auto Test::* ' from
'int'
main.cpp: message : see reference to class template instantiation
'Base<Test,0>' being compiled
我正在使用启用了 C++17 的 Visual Studio 2019。为什么构造不能自动推导?或者甚至有可能吗?
最佳答案
似乎 c++ 忘记在 TMP 中包含成员指针的自动推导。我尝试过 c++20 并失败了。这是一个大问题。但是我们可以有一个解决方法,如下所示。
struct Test {
std::string s;
};
template <typename T,typename BaseType,
BaseType (T::*groupPtr)>
struct Base{
void Process(const Test * e){
printf("%s\n", e->s.c_str());
BaseType tmp = e->*groupPtr;
printf("%s\n", tmp.c_str());
}
};
int main(){
Test t;
t.s = "x";
static constexpr auto (Test::*s)=&Test::s;
Base<Test,std::decay<decltype(std::declval<Test>().*s)>::type, s> r;
r.Process(&t);
}
上面的编码终于起作用了。关于C++自动推导模板成员指针的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64932083/