【发布时间】:2018-08-21 07:08:45
【问题描述】:
std::array<...>::size() 是非static constexpr 方法;是constexpr我可以用它作为模板参数:
#include <array>
#include <stdio>
int main(void) {
std::array<char, 12> a = {{ "Hello world" }};
std::cout << "size() = " << a.size() << ", data() = \"" << a.data() << "\"" << std::endl;
std::array<char, a.size()> b = a;
std::cout << "size() = " << b.size() << ", data() = \"" << b.data() << "\"" << std::endl;
}
但是,如果std::array<...> 是模板参数,事情就变得不确定了:
template <typename T>
void copy(T const& a) {
std::array<char, a.size()> c = a;
std::cout << "size() = " << c.size() << ", data() = \"" << c.data() << "\"" << std::endl;
}
GCC 愉快地编译了这个 [1],而 CLANG 拒绝了 [2]
<source>:6:20: error: non-type template argument is not a constant expression
std::array<char, a.size()> c = a;
[1]https://godbolt.org/z/Ru7Y3F
[2]https://godbolt.org/z/LYJcpo
根据标准,哪个是正确的?
附:
是的,我知道我可以使用 std::tuple_size 解决它:
template <typename T>
void copy(T const& a) {
std::array<char, std::tuple_size<T>::value> c = a;
std::cout << "size() = " << c.size() << ", data() = \"" << c.data() << "\"" << std::endl;
}
【问题讨论】:
-
Clang 似乎有问题。
标签: c++ c++11 templates language-lawyer constexpr