簡體   English   中英

模板類的模板化等式運算符無法編譯

[英]Templated Equality Operator for Template Class Does Not Compile

我編寫了以下代碼,目的是允許我的類mytype在編譯時選擇使用C樣式數組還是C ++ STL數組,如下所示:

#include<array>
#include<cassert>

template<bool IsTrue, typename IfTrue, typename IfFalse>
struct choose;

template<typename IfTrue, typename IfFalse>
struct choose<true, IfTrue, IfFalse> {
    typedef IfTrue type;
};

template<typename IfTrue, typename IfFalse>
struct choose<false, IfTrue, IfFalse> {
    typedef IfFalse type;
};

template<bool ArrayIsRaw>
struct mytype {
    typedef typename choose<ArrayIsRaw, int[50], std::array<int, 50>>::type array_t;
    array_t data{};
};

int main() {
    mytype<true> raw_version;
    mytype<false> stl_version;
    raw_version.data[5] = 15;
    stl_version.data[15] = 5;
    raw_version.data[10] = stl_version.data[15];
    assert(raw_version.data[10] == 5);
    return 0;
}

這樣很好。 但是,我想向此類添加一個與所涉及的基礎類型無關的相等運算符:基本上,我希望raw_version == stl_version是有效的可編譯代碼,如果每個元素相同,則返回true

但是,當我在類定義中添加以下代碼時:

template<bool Raw1, bool Raw2>
friend bool operator==(mytype<Raw1> const& a, mytype<Raw2> const& b) {
    for(size_t i = 0; i < 50; i++) if(a.data[i] != b.data[i]) return false;
    return true;
}

我收到以下錯誤:

prog.cpp: In instantiation of ‘struct mytype<false>’:
prog.cpp:32:16:   required from here
prog.cpp:24:14: error: redefinition of ‘template<bool Raw1, bool Raw2> bool operator==(const mytype<Raw1>&, const mytype<Raw2>&)’
  friend bool operator==(mytype<Raw1> const& a, mytype<Raw2> const& b) {
              ^~~~~~~~
prog.cpp:24:14: note: ‘template<bool Raw1, bool Raw2> bool operator==(const mytype<Raw1>&, const mytype<Raw2>&)’ previously defined here

我需要怎么做才能解決此錯誤?

通過將operator==兩個參數都模板化,您將為mytype<true>mytype<false>重新定義此確切的函數模板。 只需從第一個(或第二個,但不是兩個)參數中刪除模板即可完成此工作:

template<bool Raw2>    
friend bool operator==(mytype const& a, mytype<Raw2> const& b) {    
    // ...   
}

看來您choose的只是std::conditional的實現,而您可以選擇

using array_t = typename std::conditional<ArrayIsRaw, int[50], std::array<int, 50>>::type;

或對於c ++ 14

using array_t = std::conditional_t<ArrayIsRaw, int[50], std::array<int, 50>>;

暫無
暫無

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

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