[英]Static constexpr member of a template class different for each instance?
I was under the impression that static members of a class share their value between all instances of that class.我的印象是类的静态成员在该类的所有实例之间共享它们的值。 My understanding seems to be lacking though, perhaps because of the inclusion of templates or
constexpr
in this example:我的理解似乎缺乏,也许是因为在这个例子中包含了模板或
constexpr
:
#include <iostream>
#include <array>
template <typename T, std::size_t maxSize>
class Foo
{
public:
unsigned int getLen() {
return containerLen;
}
private:
static constexpr std::size_t containerLen = maxSize + 1;
std::array<T, containerLen> arr;
};
int main()
{
Foo<int, 10> foo1;
std::cout << foo1.getLen() << std::endl;
Foo<int, 12> foo2;
std::cout << foo2.getLen() << std::endl;
std::cout << foo1.getLen() << std::endl;
return 0;
}
Which gives the following output:这给出了以下输出:
11
13
11
I'm probably missing something obvious, but what is it that allows each instance of Foo
to have a different value of containerLen
?我可能遗漏了一些明显的东西,但是是什么让
Foo
每个实例具有不同的containerLen
值?
Foo<int, 10>
and Foo<int, 12>
are different classes - they just share the same template . Foo<int, 10>
和Foo<int, 12>
是不同的类——它们只是共享相同的模板。 All instances of Foo<int, 10>
will share the same containerLen
, as will all instances of Foo<int, 12>
; Foo<int, 10>
所有实例将共享相同的containerLen
, Foo<int, 12>
所有实例也是如此; but the two classes will not share a common value.但是这两个类不会共享一个共同的值。
Your error is consider Foo
a class.你的错误是认为
Foo
是一个类。
It's a class template , so Foo<int, 10>
and Foo<int, 12>
are different classes.这是一个类模板,所以
Foo<int, 10>
和Foo<int, 12>
是不同的类。
So there is a containerLen
for Foo<int, 10>
and a different containerLen
for Foo<int, 12>
.因此,有一个
containerLen
为Foo<int, 10>
和不同containerLen
为Foo<int, 12>
If you want a common static member for all class templates, you can insert it in a common base class.如果您想要所有类模板的公共静态成员,您可以将其插入到公共基类中。
The following is a simple example下面是一个简单的例子
#include <iostream>
struct Foo
{ static int value; };
int Foo::value = 0u;
template <typename T>
struct Bar : public Foo // <-- all Bar classes inherit the same value
{ };
int main()
{
Bar<int> bi;
Bar<long> bl;
bi.value = 10;
bl.value ++;
std::cout << bi.value << std::endl; // print 11
std::cout << bl.value << std::endl; // print 11
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.