2015-01-01 50 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)。 –