带有模板函数的 clang 编译错误

clang compilation error with template function

我正在编译一些代码(我用微软编写和编译的很好 工具链)与铿锵声。这是一些我不理解错误的代码:

#include <iostream>
#include <bitset>

template <int N>
auto foo(int index, std::bitset<N> & already_given)->int
{
        return 0;
}


auto bar()->void
{
        auto const n = 10;

        auto baz = std::bitset<n>{};
        for (auto i = 0; i < n; i++) {
                std::cout << foo(i, baz)
                          << std::endl;
        }
}

给我错误 no matching function to call to 'foo'。 此错误的来源是什么?

bitset<N> 是一个 class 模板,声明如下 [template.bitset]:

namespace std {
  template <size_t N> class bitset;
}

它的非类型模板参数是size_t类型,不是int,[support.types]/p6:

The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object.

因此,您应该按如下方式重写您的函数模板:

#include <cstddef> // size_t

template <std::size_t N>
//        ~~~~~~~~~~^
auto foo(int index, std::bitset<N> & already_given)->int
{
        return 0;
}

std::bitset 是一个 class 模板,它的参数是 std::size_t:

template< std::size_t N >
class bitset;

当执行 auto baz = std::bitset<n>{}; 时,n 可隐式转换为 std::size_t,但在模板参数推导期间,类型必须完全匹配 [temp.deduct.type]/p17:

If, in the declaration of a function template with a non-type template-parameter, the non-type template-parameter is used in an expression in the function parameter-list and, if the corresponding template-argument is deduced, the template-argument type shall match the type of the template-parameter exactly, except that a template-argument deduced from an array bound may be of any integral type.

非类型模板参数int N从一个整数推导出参数,它与位集的类型不匹配,因此推导失败。

要解决此问题,您需要更改参数以匹配类型:

template <std::size_t N>
auto foo(int index, std::bitset<N>& already_given) -> int;