2013-01-24 32 views
2

我試過在GCC 4.8以下代碼:文字操作模板不會在GCC 4.8工作

#include <iostream> 
using namespace std; 

template <typename T, T... vs> 
struct integral_list { 
    typedef T elem_type; 
}; 
template <typename T, T... vs> 
struct gen_array { 
    static const T data[sizeof...(vs)]; 
}; 
template <typename T, T... vs> 
const T gen_array<T, vs...>::data[sizeof...(vs)] = { vs... }; 

template <char... cs> 
constexpr auto operator "" _lit() -> integral_list<char, cs...> { 
    return declval<integral_list<char, cs...>>(); 
} 

int main() { 
    int (& data)[4] = gen_array<char, decltype("abcd"_lit)>::data; 
    for (int i = 0; i < 4; ++i) 
     cout << data[i] << endl; 
} 

,並得到

tester.cpp:21:48: error: unable to find string literal operator 'operator"" _lit' with 'const char [5]', 'unsigned int' arguments

而C++標準11說

13.5.8.5: The declaration of a literal operator template shall have an empty parameter-declaration-clause and its template-parameter-list shall have a single template-parameter that is a non-type template parameter pack (14.5.3) with element type char.

所以要麼我沒有弄清楚標準線或GCC變得奇怪。 你能幫我解決這個難題嗎? 如果沒有,是否有任何其他方式來實現字符串文字轉換爲可變參數模板的參數列表?

回答

3

不能將字面值運算符模板與字符串文字一起使用,只能使用數字文字。

§ 2.14.8第5段:

If L is a user-defined-string-literal, let str be the literal without its ud-suffix and let len be the number of code units in str (i.e., its length excluding the terminating null character). The literal L is treated as a call of the form

operator "" X (str , len) 

儘管如此,也可以做一些編譯時計算與參數字符串。簡單的例子,作爲模型可能有用:

#include <iostream> 

constexpr unsigned long operator"" _mylong(const char* s, size_t l) { 
    return l == 0 ? 0UL : (s[l - 1] - '0') + 10 * operator"" _mylong(s, l - 1); 
} 

int main() { 
    std::cout << "1492888888888888"_mylong << std::endl; 
    return 0; 
} 
+0

這不會在編譯時 – user1353535