2013-05-11 55 views
2

調用以下函數extract對g ++ 4.9.0(20130421)不起作用。我得到的錯誤是s1不是一個常量表達式。如果i可以初始化爲constexpr,那麼jk也應該如此。那是錯的嗎?字符串文字參數不被接受到constexpr函數

#include <tuple> 

template <unsigned N1, unsigned N2> 
constexpr bool strmatch(const char (&s1)[N1], const char (&s2)[N2], unsigned i = 0) 
{ 
    return (s1[i]==s2[i]) ? 
      (s1[i]=='\0') ? 
       true 
       : strmatch(s1, s2, i+1) 
      : false; 
} 

template<unsigned N> 
constexpr int extract(const std::tuple<int, int> & t1, const char (&array)[N]) { 
    return std::get<strmatch(array, "m0")>(t1); 
} 

int main(void) 
{ 
    constexpr int i = strmatch("m0", "m0"); // OK 
    constexpr int j = extract(std::make_tuple(10, 20), "m0"); 
    constexpr int k = extract(std::make_tuple(10, 20), "m1"); 

    return 0; 
} 
+0

我75%確定這是一個編譯器錯誤。函數調用替換應該清除任何引用綁定問題。 – aschepler 2013-05-11 00:15:22

回答

1

您的代碼格式不正確。問題是,array不是核心常量表達式,所以不能在調用模板參數可用於std::get

template<unsigned N> 
constexpr int extract(const std::tuple<int, int> & t1, const char (&array)[N]) { 
    return std::get<strmatch(array, "m0")>(t1); 
} 

記住constexpr功能可以在運行時調用:此代碼會在翻譯過程中(在對strmatch的調用評估中)使用運行時參數的值(array)。

+0

這真是蹩腳!我可以將strmatch的結果賦給一個constexpr整數(i),並將它用作std :: get的模板參數。我應該能夠做到這一點,而不必使用命名變量。這不是功能調用替換背後的想法嗎? – Sumant 2013-05-20 22:38:43

+0

函數調用替換僅僅是描述如何評估函數調用的形式。重申一下,你的函數'extract <3>'可以在運行時調用,如果允許的話,通常需要在運行時發生模板實例化。 – 2013-05-21 04:33:48

+0

對。但只要在編譯時可以對提取的所有調用(在翻譯單元中)進行評估,代碼就可以工作,對吧? – Sumant 2013-05-23 21:12:26

相關問題