2015-06-20 23 views
1

簡單:integer_sequence並使用默認參數值的產生如下導致硬錯誤(編譯<em>鐺 - 3.6</em>)整數序列默認參數值

#include <iostream> 
#include <utility> 

#include <cstdlib> 

template< std::size_t M, std::size_t N > // say M - arity, N - number of types 
struct test 
{ 

    template< std::size_t ...i > 
    void 
    operator() (std::index_sequence<i...> = std::make_index_sequence<M>{}) const 
    { 
     std::size_t indices[M]; 
     for (std::size_t & m : indices) { 
      m = 0; 
     } 
     for (;;) { 
      (std::cout << ... << indices[i]) << std::endl; 
      std::size_t m = 0; 
      for (;;) { 
       std::size_t & n = indices[m]; 
       ++n; 
       if (n != N) { 
        break; 
       }   
       n = 0; 
       if (++m == M) { 
        return; 
       } 
      } 
     } 
    } 

}; 

int 
main() 
{ 
#if 0 
    test< 3, 3 >{}(); // hard error 
#else 
    test< 3, 3 >{}(std::make_index_sequence<3>{}); // ugly workaround 
#endif 
    return EXIT_SUCCESS; 
} 

這看起來很奇怪,因爲簡單的替換按預期工作。

這是爲什麼?爲什麼默認參數不能在上面的情況下分配,但明確的分配工作?

追加const &&&參數類型什麼也不做。

+0

顯示錯誤... –

+0

@LightnessRacesinOrbit http://coliru.stacked-crooked.com/a/14a759868ea02e34 – Orient

+0

似乎期望它確切類型的等價性。 'std :: make_index_sequence < M > ::運算符std :: index_sequence < i... >()const'將是非常有用的功能。 – Orient

回答

2

模板參數不能從默認參數推導出來。這就是爲什麼我們通常構建序列之前委託給一個輔助函數:

void operator()() const { 
    helper(std::make_index_sequence<M>{}); 
} 

template<std::size_t... i> 
void helper(std::index_sequence<i...>) const; 
+0

這種限制的根本原因是什麼? – Orient

+0

@Oient該標準只是簡單地將其列爲非推導的上下文。我沒有意識到它的基本原理,直到我閱讀這個http://stackoverflow.com/a/9629112/701092 – 0x499602D2

+0

鏈接exmaple對我來說不清楚。 – Orient