我编写了以下代码,旨在让我的类 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>>;
关于c++ - 模板类的模板化相等运算符不编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44683961/