2015-01-01 49 views
1

我正在编译一些代码(我编写并使用微软 工具链编译)与铿锵。下面是一些一段代码,我不理解的错误:铿锵编译与模板函数的错误

#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'。 这个错误的来源是什么?

+0

微软的工具链或铛(使用MS编译器)?什么请求? –

+0

@πάνταῥεῖ我编辑过。谢谢。 – mookid

回答

6

std::bitset是一个类模板,它带有其参数为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从一个整数推导出参数,它不匹配bitset的类型,所以你有一个扣除失败。

要解决这个问题,你需要改变你的参数相匹配的类型:

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

bitset<N>是类模板声明如下[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; 
} 
+0

需要额外的报价,说明为什么这种类型的不匹配会导致扣除失败([temp.deduct.type]/p17)。 –