为什么C ++不支持模板(非静态)成员变量? [英] Why are template (non-static) member variables not supported in C++?
问题描述
虽然可以在C ++ 14中将静态成员变量模板化,但这将无法工作:
While static member variables can be templated in C++14 this wont work:
class SomeClass
{
public:
template<typename T>
T var = {};
};
int main()
{
SomeClass instance;
instance.var<int> = 50;
instance.var<double> = 0.1;
}
原因是什么,C ++不支持变量成员的模板
What are the reasons, that templates for variable members are not supported by the C++ standard since it should be possible in principle?
推荐答案
在原理上或实践上不可能 ,如其他答案所解释: sizeof(SomeClass)
通常将无法计算,而 SomeClass
将不再计算具有任何可预测的或理智的身份,从而破坏了其存在的目的。
It cannot be possible in principle or in practice, as the other answers explain: sizeof(SomeClass)
would be impossible to compute in general, and SomeClass
would no longer have any predictable or sane identity, defeating the purpose of its existence.
如果只有少数几种类型希望从中选择,并且希望更改选择类型,也许您正在寻找 variant ?
If there are only a select few types you wish to choose from, and you wish to change the "selected" type at runtime, perhaps a variant is what you're looking for?
#include <variant>
class SomeClass
{
public:
std::variant<int, double> var = {};
};
int main()
{
SomeClass instance;
instance.var = 50;
instance.var = 0.1;
}
(此需要C ++ 17 ,但已经有很多年了等效的Boost。)
(This requires C++17, but a Boost equivalent has been available for many, many years.)
它之所以有效,是因为 var
会和存储 一个 int所需的大小一样大
或 double
(加上一些内务处理),无论您的变体在任何给定时间处于哪种模式,此大小都是固定的。
It works because var
will be as big as it needs to to store either an int
or a double
(plus some housekeeping), and this size is fixed no matter which "mode" your variant is in at any given time.
如果要接受任何类型,则可以使用 std :: any
,就像毒品的变体一样。开销比较重,但是如果您的需求真的很放松,那么就可以完成工作。
If you want to accept any type, you could use std::any
, which is like a variant on drugs. The overhead is a little heavier, but if your requirements are really so relaxed then this can do the job.
但是如果您想要多个变量,有多个变量。
But if you want multiple variables, have multiple variables.
这篇关于为什么C ++不支持模板(非静态)成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!