声明时的默认值

时间:2012-07-12 08:00:43

标签: c++ templates

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

class MyClass
{
   MyInt<1> my_int;
};

有没有实现这个的库?

1 个答案:

答案 0 :(得分: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;以获得看似int的内容,但以值11开头。

相关问题