微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

模板推导类型和显式指示类型有什么区别

如何解决模板推导类型和显式指示类型有什么区别

Context:试图创建一个类来解包一个元组(用于存储可变参数模板参数)。受到这个答案的启发https://stackoverflow.com/a/24804339/11510510我有一些可以完成这项工作的东西。

(如果不是,我只能使用 C++11,否则我将使用 C++17 中的 std::apply)

问题:它仅在使用特定类型创建对象时才编译,而不是在模板内部。

要实例化的目标类

    template<class C,class ...Args>
    struct APPLY_TUPLE{};
    
    template<class C,class ...Args>
    struct APPLY_TUPLE<C,std::tuple<Args...>>{
        // irrelevant code
    };

实例化 APPLY_TUPPLE 的类

    template<typename C,typename R>
    struct TupledCall
    {     
        TupledCall(C& obj) : object{obj} {}
     
        R MethodTrigger(){
             // instantiate APPLY_TUPLE here with type of object        
        }

        C &object;
    };

/*Instantiation as*/
auto obj = Summator();
auto tupledCall = TupledCall<Summator,int>(obj);
tupledCall.MethodTrigger();

编译什么

R MethodTrigger(){
    tuple<int,int,int> list = make_tuple(1,5,4);

    auto tup = APPLY_TUPLE<Summator,args(list)>(object);
    return tup.delayed_call<int,&Summator::sum>(list);
}

R MethodTrigger(){
    tuple<int,4);
    
    Summator s = Summator();
    auto tup = APPLY_TUPLE<typename decay<decltype(s)>::type,&Summator::sum>(list);
}

什么不能编译

R MethodTrigger(){
    tuple<int,4);

    auto tup = APPLY_TUPLE<C,4);
    
    auto tup = APPLY_TUPLE<typename decay<decltype(object)>::type,4);
    
    C sum = C(); // C should be deducted as Summator in this template
    auto tup = APPLY_TUPLE<typename decay<decltype(object)>::type,&Sumator::sum>(list);
}

它们之间有什么区别?为什么在尝试使解决方案通用时无法编译?

编译器错误

    <source>: In member function 'R TupledCall<C,R>::MethodTrigger()':
<source>:80:37: error: expected primary-expression before 'int'
   80 |             return tup.delayed_call<int,&Summator::sum>(list);
      |                                     ^~~
<source>:80:37: error: expected ';' before 'int'
<source>:80:41: error: expected unqualified-id before ',' token
   80 |             return tup.delayed_call<int,&Summator::sum>(list);
      |                                         ^
<source>:80:57: error: qualified-id in declaration before '>' token
   80 |             return tup.delayed_call<int,&Summator::sum>(list);

最小可重现示例 https://godbolt.org/z/bPYWhfM7d

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。