使用constexpr函数的结果作为模板参数(clang vs gcc)

时间:2017-03-28 14:32:27

标签: c++ templates clang constexpr

请看下面的代码,抱歉有点冗长,但我尽力用最小的例子重现问题(还有一个live copy)。在那里我基本上有一个返回字符串文字大小的元函数,以及包装它的constexpr函数。然后当我在模板参数中调用这些函数时,gcc(5.4,6.2)对它很满意,但clang(3.8,3.9)barfs与&#34;非类型模板参数不是常量表达式&#34;在strsize(s)的测试正文中。如果我用str_size<S>代替,两个编译器都很高兴。所以问题是:

  1. 这对clang或我的代码是否有问题?

  2. 使用constexpr函数在clang和gcc上编译它的方法是什么?

    template<size_t N> using string_literal_t = char[N];
    
    template<class T> struct StrSize; ///< metafunction to get the size of string literal alikes 
    
    /// specialize StrSize for string literals
    template<size_t N>
    struct StrSize <string_literal_t<N>>{ static constexpr size_t value = N-1; };
    
    /// template variable, just for convenience
    template <class T>
    constexpr size_t str_size = StrSize<T>::value;
    
    /// now do the same but with constexpr function
    template<class T>
    constexpr auto strsize(const T&) noexcept-> decltype(str_size<T>) {
       return str_size<T>;
    }
    
    template<class S, size_t... Is>
    constexpr auto test_helper(const S& s, index_sequence<Is...>) noexcept-> array<char, str_size<S>> {
       return {s[Is]...};
    }
    
    template<class S>
    constexpr auto test(const S& s) noexcept-> decltype(auto) {
    // return test_helper(s, make_index_sequence<str_size<S>>{}); // this work in both clang and gcc
       return test_helper(s, make_index_sequence<strsize(s)>{});  // this works only in gcc
    }
    
    auto main(int argc, char *argv[])-> int {
       static_assert(strsize("qwe") == 3, "");
       static_assert(noexcept(test("qwe")) == true, "");
    
       return 0;
    }
    

0 个答案:

没有答案
相关问题