繁体   English   中英

将调用 class 的“this”或“type”隐式传递给非成员模板 function

[英]Implicitly pass the "this" OR the "type" of the calling class to a non-member template function

有没有办法将调用 class 的this隐式传递给被调用的模板 function?

到目前为止,我尝试了以下方法:

template<class P, class T>
void funcA(P& p, T const* t = this){   //<--does not work.
    //...some code here...
}

class TypeX { }

class TypeA {
public: 
    void DoSomething(){
        TypeX x;
        funcA(x, this);   //compiles fine
        //funcA(x);       //<---my goal: implicitly pass "this" by default.

    }
}

void main(){
    
    TypeA objX;
    
    objX.DoSomething();
    
}

对于type-of-"this" ,到目前为止,我做了以下工作:

template<class T, class P>
constexpr auto funcA(P& p) {
    //...some code here that also uses type T...
}

class TypeA {
    public: 
        void DoSomething(){
            TypeX x;
            funcA<TypeA>(x);   //<---explicitly passing TypeA. (compiles)
            //funcA(x);        //<---my goal.
            //funcA<>(x);      //<---my goal(fair enough)
        }
    }
}

如您所见,我明确地将TypeA传递给funcA 对我来说似乎是多余的。 尽管它目前在我的项目中运行良好,但我尝试通过将funcA<TypeA>(x)设置为funcA(x) ) 来使其更清洁。 但到目前为止还没有成功。 我希望仍然可以做到这一点,所以我在这里问。

你在评论中说,

funcA必须是 class 的非成员,特别是目标 class 将被调用。

鉴于此,不可能将this用作 function 的参数的默认值。


我认为以下内容没有任何问题:

template<class P, class T>
void funcA(P& p, T const* t){
    //...some code here...
}

class TypeX { };

class TypeA {
public: 
    void DoSomething(){
        TypeX x;
        funcA(x, this);   // Explicitly pass "this".
    }
};

它也不繁重。

暂无
暂无

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

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