没有为带有初始化器的static const成员提供定义? [英] No definition available for static const member with initializer?

查看:232
本文介绍了没有为带有初始化器的static const成员提供定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定:

template<class T>
struct S {
  static int const N = 1;
};

extern template class S<int>;

template<class T>
int f( T n ) {
  return n + S<T>::N; // line 10
}

int main() {
  return f(1);        // line 14
}

//template class S<int>; // intentionally commented out to trigger error

我得到:

foo.cpp: In function ‘int f(T) [with T = int]’:
foo.cpp:10:   instantiated from ‘const int S<int>::N’
foo.cpp:10:   instantiated from ‘int f(T) [with T = int]’
foo.cpp:14:   instantiated from here
foo.cpp:10: error: explicit instantiation of ‘S<int>::N’ but no definition available

为什么会收到错误吗?


  1. 执行显式模板实例化声明的意义是定义可以在别处,而编译器(不是链接器)会给出错误。 (在实际应用中,目前注释掉的显式实例化声明将在另一个翻译单元中)

  2. 在这种情况下,该值具有常量初始值所以编译器在理论上可以直接使用值。

  3. 当我不做显式模板实例化声明时,我(奇怪)不必显式定义 S T :: N

  1. The point of doing an explicit template instantiation declaration is so that the definitions can be elsewhere, yet the compiler (not the linker) gives an error. (In a real application, the currently commented out explicit instantiation declaration would be in another translation unit anyway.)
  2. In this case, the value has a constant initializer so the compiler can in theory simply use the value directly.
  3. When I don't do the explicit template instantiation declaration, I (oddly) don't have to explicitly define S<T>::N.

这是在Mac OS上使用g ++ 4.2.1 X 10.6.6。

This is with g++ 4.2.1 on Mac OS X 10.6.6.

推荐答案

extern template class S<int>;

我认为这行会导致错误,因为它告诉编译器查找 S< int> 在某处,但不存在明确的实例化。因此错误。

I think this line causes the error, as it tells the compiler to look for explicit instantiation of S<int> somewhere, but no explicit instantiation exists. Hence the error.

一旦你注释了这一行,我认为代码应该编译好。

Once you comment this line, I think the code should compile fine.

编辑:

好吧,看到这个: http://www.ideone.com/oQnOi

正如我所说,它编译得很好!

As I said, it compiles fine!

编辑:

我认为$ 9.4.2 / 4 B 不适用于模板类的静态成员,因为$ 14.5.1.3 [temp.static]不要求在命名空间范围中定义静态成员:

I think $9.4.2/4 (as quoted by Mark B) doesn't apply to the static members of class templates, as $14.5.1.3 [temp.static] doesn't mandate the static members to be defined at namespace scope:


静态数据成员的定义
可以在命名空间范围内提供
定义 static
成员的类模板

A definition for a static data member may be provided in a namespace scope enclosing the definition of the static member’s class template.

示例如下:

template<class T> class X  { static T s; }; 
template<class T> T X<T>::s = 0;

注意,它不说必须提供 可以提供。所以我认为在命名空间范围的类模板的静态成员的定义是可选的。

Notice, it doesn't say "must be provided", rather "may be provided". So I think the definition of static members of class template at namespace scope is optional.

这篇关于没有为带有初始化器的static const成员提供定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆