模板类的模板化相等运算符未编译 我编写了以下代码,允许我的类, >在编译时选择是否使用C样式数组或C++ STL数组,如::/P> #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; }
我得到以下错误:模板类的模板化相等运算符未编译 我编写了以下代码,允许我的类, >在编译时选择是否使用C样式数组或C++ STL数组,如::/P> #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; },c++,templates,template-meta-programming,C++,Templates,Template Meta Programming,我得到以下错误: 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
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
prog.cpp:在“struct mytype”的实例化中:
程序cpp:32:16:从此处开始需要
程序cpp:24:14:错误:重新定义“模板布尔运算符==(常量mytype&,常量mytype&)”的
友元布尔运算符==(mytype常量和a、mytype常量和b){
^~~~~~~~
prog.cpp:24:14:注意:“模板布尔运算符==(constmytype&,constmytype&)”,前面在这里定义
我需要做什么来修复此错误?通过将
运算符==
的两个参数都设置为模板,您正在为mytype
和mytype
重新定义此确切的函数模板。只需从第一个(或第二个,但不是两个)参数中删除模板即可:
template<bool Raw2>
friend bool operator==(mytype const& a, mytype<Raw2> const& b) {
// ...
}
或者对于c++14
using array_t = std::conditional_t<ArrayIsRaw, int[50], std::array<int, 50>>;
使用数组\u t=std::conditional\u t;
using array_t = typename std::conditional<ArrayIsRaw, int[50], std::array<int, 50>>::type;
using array_t = std::conditional_t<ArrayIsRaw, int[50], std::array<int, 50>>;