gpt4 book ai didi

c++ - 可以根据c++中的模板args更改类成员吗

转载 作者:行者123 更新时间:2023-12-03 06:51:31 24 4
gpt4 key购买 nike

我希望可以根据模板参数更改类成员。
我想要类似的东西

template<int value>
class MyClass
{
public:
void print()
{
// using the member
std::cout << sizeData() << std::endl;
for (int i=0;i<sizeData();i++)
{
std:cout << data[i] << std::endl;
}
}
static int sizeData()
{
#if value == 1
return 3;
#endif
#if value == 2
return 6;
#endif
}
static int sizeArray()
{
#if value == 1
return 40;
#endif
#if value == 2
return 200;
#endif
}
private:
#if value == 1
int data[3];
const static int array[40];
#endif
#if value == 2
int data[6];
const static int array[200];
#endif
}
不知道能不能用c++实现。
谢谢你的时间。
添加
许多先生已经在 C++11 和 C++17 中给出了答案。谢谢你的所有建议。
如果代码能用C++98解决就完美了。因为我的代码应该在只支持 C++98 的平台上运行。

最佳答案

您可以使用 std::conditional 选择您想要的成员

template<int value>
class MyClass
{
public:
static int sizeData()
{
return (value == 1) ? 3 : 6; // needs to be improved
}
static int sizeArray()
{
return sizeof(array) / sizeof(array[0]); // size of array divided by size of element is then number of elements in the array
}
private:

std::conditional_t<value == 1, int[3], int[6]> data;
const static std::conditional_t<value == 1, int[40], int[200]> array;

};

虽然 std::conditional不是 C++98 的一部分,它仅使用 C++98 C++ 实现,因此您可以使用引用站点链接中的可能实现来实现自己。你可以看到与
#include <iostream>

template<bool B, class T, class F>
struct conditional { typedef T type; };

template<class T, class F>
struct conditional<false, T, F> { typedef F type; };

template<int value>
class MyClass
{
public:
static int sizeData()
{
return (value == 1) ? 3 : 6; // needs to be improved
}
static int sizeArray()
{
return sizeof(array) / sizeof(array[0]);
}
private:

typename conditional<value == 1, int[3], int[6]>::type data;
const static typename conditional<value == 1, int[40], int[200]>::type array;

};

int main()
{
MyClass<1> m;
std::cout << m.sizeData();
}
在此 live example .

对于 sizeData来说这种分崩离析自 data不是 static但功能是。为避免代码重复,请不要使用 std::conditional ,我们可以使用 enum 技巧来获取数组大小的编译时常量,并使用类似的方法
#include <iostream>

template<int value>
class MyClass
{
public:
static int sizeData()
{
return data_size; // now improved
}
static int sizeArray()
{
return array_size;
}
private:
enum { data_size = (value == 1) ? 3 : 6 }; // this is required to be a compile time constant
enum { array_size = (value == 1) ? 40 : 200 }; // these need to become before the array members
int data[data_size]; // less verbose
const static int array[array_size];
};

int main()
{
MyClass<1> m;
std::cout << m.sizeData();
}


关于c++ - 可以根据c++中的模板args更改类成员吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64245909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com