c++ - 声明时的默认值

标签 c++ templates

有没有办法在声明时在类声明中声明对象的值(我对 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/

相关文章:

c++ - 如何从 vector 迭代的变换构造元组

c++ - STL 映射输出迭代器查找值

c++ - 具有包扩展的可变参数函数模板不在最后一个参数中

c++ - 为什么派生类可以调用基类的成员函数?

c++ - 使用mingw构建库时如何生成pdb文件?

c++ - 用随机数初始化二维数组

c++ - const char* 的模板方法特化

c++ - 使用scoped_ptr解压可变参数模板

c++ - 使用预处理器指令来定义美元符号代表什么会导致任何冲突吗?

c++ - 在 C++ 编程中编写函数 ASTERISK