c++ - 模板类的模板化相等运算符不编译

标签 c++ templates template-meta-programming

我编写了以下代码,旨在让我的类 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/

相关文章:

c++ - 我可以对(非成员)函数使用部分模板特化吗?

c++ - 无符号字符模板值溢出

c++ - 如何编写计算整数和的可变参数模板类的通用版本

c++ - 没有开关盒的简单计算器的新想法

C++在函数声明中错误两种或多种数据类型

c++ - SHCreateStreamOnFileEx 大于 2**32 字节的文件

python - 模板中的 django forloop 计数器

c++ - 如何使用模板在 C++ 中创建不同的构造函数?

c++ - 如何检测类型是否可以流式传输到 std::ostream?

c++ - 通过引用 C++ 中的构造函数传递堆栈分配的值