有没有办法在声明时在类声明中声明对象的值(我对 int
/double
感兴趣)?像这样:
class MyClass
{
MyInt<1> my_int;
};
是否有实现此功能的库?
最佳答案
在 C++11 中,您可以在类定义中提供默认初始化器:
struct Foo
{
int a = 11;
Foo() = default; // still a trivial class :-)
};
在以前,您必须使用构造函数初始化程序:
struct Bar
{
int b;
Bar() : b(11) { } // non-trivial constructor :-(
};
用法:
Foo x;
Bar y;
assert(x.a == 11 && y.b == 11);
也许您会发现@Msalters 的解决方案很有用:
template <typename T, T InitVal>
struct InitializedType
{
typedef T type;
static type const initial_value = InitVal; // with restrictions
type & operator() { return x; }
type const & operator() const { return x; }
InitializedType() : x(Initval) { }
private:
type x;
};
现在您可以添加 InitializedType<int, 11> n;
得到看起来像 int
的东西但以值 11
开始.
关于c++ - 声明时的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11447431/