0

有没有办法在声明时在类声明中声明对象的值(我对int/感兴趣)?double像这样的东西:

class MyClass
{
   MyInt<1> my_int;
};

有没有实现这个的图书馆?

4

1 回答 1

3

在 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;以获取看起来像 anint但以 value 开头的东西11

于 2012-07-12T08:03:36.827 回答