C++自动推导模板成员指针的类型

标签 c++ templates c++17 language-lawyer

我有这个代码:

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 并失败了。这是一个大问题。但是我们可以有一个解决方法,如下所示。

  • 考虑您的代码应该可以工作,但不是由于“c++ 限制”。我们只会修改其中的一部分。请按以下步骤操作。
    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/

    相关文章:

    c++ - 子类调用意外的重载函数

    c++ - 使用模板特化选择合适的类型

    c++ - 如何将 boost::string_view 转换为 std::string_view?

    c++ - 模板化转换运算符优先级

    c++ - 仅当类有一个特定方法时如何调用?

    c++ - `snprintf_s` 错误的安全感

    c++ - 如何使用指针在 C 中重用数组变量

    c++ - 从类型包中解压缩模板-模板参数

    templates - 通过 HStringTemplate 生成带有一些逻辑的模板

    c++ - 函数指针和模板