【问题标题】:Declare class and it's static const in macro声明类,它是宏中的静态常量
【发布时间】:2014-04-05 07:37:29
【问题描述】:

我有课

struct testdb1 {
    typedef tuple<int, double> value_type;
    static const value_type data[];
};
const testdb1::value_type testdb1::data[] = {
    make_tuple(1, 1.1),
    make_tuple(2, 2.2),
    make_tuple(3, 3.3),
    make_tuple(3, 3.3)

};

现在,我希望能够以更紧凑的方式定义它,我想像这样:

STATIC_DB(
    testdb1,
    make_tuple(1, 1.1),
    make_tuple(2, 2.2),
    make_tuple(3, 3.3),
    make_tuple(3, 3.3)
)

我想宏是要走的路,但我不知道如何写(如果可能的话)这样的东西。如果可以用模板做到这一点,那就更好了,但我不明白怎么做。

提前感谢您的帮助

【问题讨论】:

  • 你的宏几乎一无所获
  • 让我免于打字。 如果有可能,为什么不使用呢?
  • 您引入了代码/符号,必须对其进行检查以了解其背后的目的。省略使代码更清晰(没有额外的信息可以理解)

标签: c++ c++11 macros


【解决方案1】:

使用constexpr,您可以执行以下操作(简洁明了):

struct testdb1 {
    static constexpr tuple<int, double> data[] =
    {
        make_tuple(1, 1.1),
        make_tuple(2, 2.2),
        make_tuple(3, 3.3),
        make_tuple(3, 3.3)
    };
};

【讨论】:

  • 是的,但我需要做 constexpr testdb1::value_type testdb1::data[];无论如何:/但仍然最接近我想要的
【解决方案2】:

可能有更好的方法来做到这一点,但你可以像这样使用

#define TUPLE(first,second) make_tuple(first,second),
#define TUPLE_LAST(first,second) make_tuple(first,second)
#define STATIC_DB(type,tuples) \
        struct type{\
                typedef tuple<int,double> value_type;\
                static const value_type data[];\
        };\
        const type::value_type type::data[]=\
                tuples;

STATIC_DB(
    testdb1,
    {
        TUPLE(1, 1.1)
        TUPLE(2, 2.2)
        TUPLE(3, 3.3)
        TUPLE_LAST(3, 3.3)
    }
)

格式化输出:

struct testdb1{ 
    typedef tuple<int,double> value_type; 
    static const value_type data[]; 
}; 

const testdb1::value_type testdb1::data[]= { 
      make_tuple(1,1.1), 
      make_tuple(2,2.2), 
      make_tuple(3,3.3), 
      make_tuple(3,3.3) 
};

【讨论】:

    【解决方案3】:

    你可以试试这个:

    #define STATIC_DB(t1_, t2_, T_, ...)                                    \
        struct T_ {                                                         \
            typedef tuple<t1_, t2_> value_type;                             \
            static const value_type data[];                                 \
        };                                                                  \
        const T_::value_type T_::data[]   = {                               \
            __VA_ARGS__                                                     \
        };
    
    STATIC_DB(int, double, testDB, make_tuple(1, 1.1), make_tuple(2, 2.2) );
    

    【讨论】:

      猜你喜欢
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      • 2021-10-30
      相关资源
      最近更新 更多