簡體   English   中英

模板推導需要用戶定義的隱式轉換的方案

[英]Scenarios where template deduction requires user-defined implicit conversion

我有一個包含重載運算符模板和隱式轉換構造函數的類模板,類似於以下內容:

#include <utility>

template <class A, class B>
class X {
public:
    A a;
    B b;

    X(A a, B b) : a(a), b(b) {}
    X(std::pair<A, B> &value) : a(value.first), b(value.second) {}

    template <class C>
    friend X<A, C> operator+(const X<A, B> &left, const X<B, C> &right) {
        return X<A, C>(left.a, right.b);
    }
};

int main() {
    X<int, int> a(1, 2);
    X<int, float> b(1, 2.5f);
    std::pair<int, float> c(1, 2.5f);

    a + b; // Valid
    a + c; // Template deduction error
}

我在另一個問題上找到了這個答案,但是在這里我看不到任何實現該解決方案的方法。 (請注意,重要的是第一個參數的第二個模板參數和第二個參數的第一個模板參數是相同的,實際的運算符實現不是那么簡單,而是接口是相同的。

@ R-Sahu和您引用的鏈接已經回答了您的問題。 但是一種解決方案是為非X類型提供另一個運算符+,以便在扣除C之后進行轉換,

#include <utility>

template <class A, class B>
class X {
public:
    A a;
    B b;

    X(A a, B b) : a(a), b(b) {}
    X(const std::pair<A, B> &value) : a(value.first), b(value.second) {}


    template <class C,template <typename, typename> typename O >
    friend X<A, C> operator+(const X<A, B> &left, const O<B, C> &right) {
       return left + X<B,C>(right);
    }
    template <class C>
    friend X<A, C> operator+(const X<A, B> &left, const X<B, C> &right) {
       return X<A, C>(left.a,right.b);
    }
};


int main() {
    X<int, int> a(1, 2);
    X<int, float> b(1, 2.5f);
    std::pair<int, float> c(1, 2.5f);

    a + b; // Valid
    a + c; // Works
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM