GCC 4.7有时无法使用指针模板参数
gcc 4.7 fails to use pointer template parameter sometimes
完成(不)工作示例:
struct s { int i; };
template<const s* _arr>
class struct_array
{
public:
static constexpr auto arr = _arr[0]; // works
template<int >
struct inner // line 9, without this struct, it works
{
};
};
constexpr const s s_objs[] = {{ 42 }};
int main()
{
struct_array<s_objs> t_obj;
return 0;
}
这样编译:
g++ -std=c++11 -Wall constexpr.cpp -o constexpr
我使用Ideone的GCC 4.8.1获得了一个运行程序,但是4.7.3向我打印出来:
constexpr.cpp: In instantiation of ‘class struct_array<((const s*)(& s_objs))>’:
constexpr.cpp:18:30: required from here
constexpr.cpp:9:16: error: lvalue required as unary ‘&’ operand
constexpr.cpp:9:16: error: could not convert template argument ‘(const s*)(& s_objs)’ to ‘const s*’
最后两行重复3次。原因是什么,是否有任何解决方法可以在GCC 4.7.3上使用我的代码?
这似乎是我的编译器错误。
我在GCC 4.1.2(codepad)上尝试了您的示例,您必须明确注意该变量为具有外部链接(const暗示内部链接,除非另外指定,否则以下代码为C 03):
struct s { int i; };
template<const s* _arr>
class struct_array
{
public:
static const s arr;
template<int >
struct inner
{
};
};
template<const s* _arr>
const s struct_array<_arr>::arr = _arr[0];
// Notice the 'extern'
extern const s s_objs[] = {{ 42 }};
int main()
{
struct_array<s_objs> t_obj;
return 0;
}
我还可以在启用C 11的GCC 4.8.1上工作。
所以,解决方法是:
更改
constexpr const s s_objs[] = ...;
to
extern const s s_objs[] = ...;
现场示例在这里。
如果您希望变量是静态类成员,则必须指定它具有外部链接:
struct data
{
static const s s_objs[1];
};
extern const s data::s_objs[1] = {{ 42 }};
这给了我对GCC 4.7的警告,而不是4.8。另外,它不会在Rise4Fun上编译。因此,我不确定这是一个编译器中的纯标准还是错误。
相关文章:
- 为函数定义符号不明确的指针参数
- 构造函数 (C++) 中的 char 指针参数存在问题
- 按引用调用与按指针参数调用的差异 前递增和后递增
- 为什么具有指针参数的成员函数需要指向指针的指针?
- 通过引用函数传递指针参数是什么意思?
- 从double到double*的指针参数
- void 函数中的指针参数返回不一致的值
- 无法向上转换指针到指针参数
- 将数组动态分配到具有指针参数的函数中
- 模板函数指针参数与构造函数参数
- 使用通用函数指针参数化函数模板的简洁方法
- 如何为C++字符串分配空指针参数?
- C++带有指针参数的函数
- 指针参数的默认值
- 将常量添加到函数模板指针参数
- 如何传递unique_ptr<T>代替原始*输出*指针参数?
- 不带星号的函数指针参数
- 功能指针参数参数转换为const
- 将指针参数传递给双指针参数
- 如何调试指针参数是否通过函数修改