簡體   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