运算符重载导致模板参数推导失败

时间:2019-02-23 09:06:05

标签: c++ templates template-deduction

我有以下示例代码,它们可以在Visual Studio中很好地编译,但不能在GCC 6中编译。我理解它可能与模板参数推导失败有关,但是我想不出解决该问题的正确解决方案。

#include <iostream>
#include <array>

//using namespace std;
namespace 
{
    template <int T>
    std::array<char, T> operator&(const std::array<char, T>& l, const std::array<char, T>& r)
    {
        std::array<char, T> result{};

        return result;
    }

}
int main()
{
    std::array<char, 4> result{};
    std::array<char, 4> value{};
    std::array<char, 4> mask{};
    result = value & mask;
    return 0;
}

编译输出

main.cpp: In function ‘int main()’:
main.cpp:29:20: error: no match for ‘operator&’ (operand types are ‘std::array’ and ‘std::array’)
 result = value & mask;
                ^
main.cpp:16:25: note: candidate: template std::array {anonymous}::operator&(const std::array&, const std::array&)
 std::array<char, T> operator&(const std::array<char, T>& l, const std::array<char, T>& r)
                     ^
main.cpp:16:25: note:   template argument deduction/substitution failed:
main.cpp:29:22: note:   mismatched types ‘int’ and ‘long unsigned int’
 result = value & mask;
                  ^
main.cpp:29:22: note:   ‘std::array’ is not derived from ‘const std::array’
In file included from /usr/include/c++/5/ios:42:0,
             from /usr/include/c++/5/ostream:38,
             from /usr/include/c++/5/iostream:39,
             from main.cpp:9:
/usr/include/c++/5/bits/ios_base.h:165:3: note: candidate: constexpr 
std::_Ios_Iostate std::operator&(std::_Ios_Iostate, std::_Ios_Iostate)
operator&(_Ios_Iostate __a, _Ios_Iostate __b)
^
/usr/include/c++/5/bits/ios_base.h:165:3: note:   no known conversion for 
argument 1 from ‘std::array’ to ‘std::_Ios_Iostate’
/usr/include/c++/5/bits/ios_base.h:125:3: note: candidate: constexpr 
std::_Ios_Openmode std::operator&(std::_Ios_Openmode, std::_Ios_Openmode)
operator&(_Ios_Openmode __a, _Ios_Openmode __b)
^
/usr/include/c++/5/bits/ios_base.h:125:3: note:   no known conversion for 
argument 1 from ‘std::array’ to ‘std::_Ios_Openmode’
/usr/include/c++/5/bits/ios_base.h:83:3: note: candidate: constexpr 
std::_Ios_Fmtflags std::operator&(std::_Ios_Fmtflags, std::_Ios_Fmtflags)
operator&(_Ios_Fmtflags __a, _Ios_Fmtflags __b)
^
/usr/include/c++/5/bits/ios_base.h:83:3: note:   no known conversion for 
argument 1 from ‘std::array’ to ‘std::_Ios_Fmtflags’

非常感谢您能给我一个解决建议。

1 个答案:

答案 0 :(得分:1)

Template argument deduction由于类型不匹配而失败; std::array的第二个非类型模板参数的类型为std::size_t

(重点是我的)

  

如果在参数列表中使用了非类型模板参数,并且推导了相应的模板参数,则推导的模板参数的类型(如其随附的模板参数列表中指定的那样,意味着保留引用)。必须与非类型模板参数的类型完全匹配,...

将非类型参数从int更改为std::size_t

template <std::size_t T>
std::array<char, T> operator&(const std::array<char, T>& l, const std::array<char, T>& r)
{
    std::array<char, T> result{};

    return result;
}