Dom*_*fer 5 c++ template-meta-programming
我在C++类中有以下代码:
class Features
{
#define Feature_Size_A 12345
#define Feature_Size_B 45678
#define Feature_Size_C 78901
//#define Feature_Size_D 14725
const int Feature_Sum = 0
#ifdef Feature_Size_A
+ Feature_Size_A
#endif
#ifdef Feature_Size_B
+ Feature_Size_B
#endif
#ifdef Feature_Size_C
+ Feature_Size_C
#endif
#ifdef Feature_Size_D
+ Feature_Size_D
#endif
;
#ifdef Feature_Size_A
static float Feature_A[Feature_Size_A];
#endif
#ifdef Feature_Size_B
static float Feature_B[Feature_Size_B];
#endif
#ifdef Feature_Size_C
static float Feature_C[Feature_Size_C];
#endif
#ifdef Feature_Size_D
static float Feature_D[Feature_Size_D];
#endif
};
Run Code Online (Sandbox Code Playgroud)
我过去常常注释掉第4行的功能来编译和运行不同的测试.但是现在我想将类作为模板,因此我可以在同一个程序中实例化具有不同功能的多个版本.
我在考虑这样的事情:
template <bool Feature_A, bool Feature_B, bool Feature_C, bool Feature_D>
class Features
{
...
};
Features<true, true, true, false> f;
Run Code Online (Sandbox Code Playgroud)
我尝试使用boost :: mpl:vector's但我正在苦苦挣扎.
顺便说一句:这不是完整的代码.原始代码有25个功能.
我很感谢每个不涉及宏的想法:-)
类型列表可以用来解决这个问题。
template<unsigned num, unsigned size, typename T>
class Feature : public T
{
public:
static float feature[size];
static const unsigned int feature_sum = size + T::feature_sum;
};
template<unsigned num, unsigned size, typename T>
float Feature<num, size, T>::feature[size];
class Tail {
public:
static const unsigned feature_sum = 0;
};
template<unsigned num, unsigned size, typename T>
float* get_feature_arr(Feature<num, size, T>& ref)
{
return ref.feature;
}
int main() {
Feature<1, 12345, Feature<2, 45678, Feature<4, 78901, Tail>>> TripleFeatures;
auto first = get_feature_arr<1>(TripleFeatures);
auto third = get_feature_arr<4>(TripleFeatures);
auto size = TripleFeatures.feature_sum;
}
Run Code Online (Sandbox Code Playgroud)
这也可用于访问任何功能,无论列表中是否包含其他功能。
编辑:我删除了一些细节,例如不定义数组并尝试将“3features”作为标识符。勒固定。代码编译 GCC 4.7.1。