gpt4 book ai didi

c++ - 可变参数模板且没有值

转载 作者:可可西里 更新时间:2023-11-01 18:36:42 26 4
gpt4 key购买 nike

模板非常适合编写模板函数和类,因此我们可以使用它来缩短我们的代码并让编译器为我们做一些工作。

在我的例子中,我想使用一个模板类,例如。

template <typename T, typename G> class unicorn {
T value01;
G value02; <- not used in ever instance of class unicorn
};

有没有办法让编译器创建一个类型名称为 T = int 的实例,例如如果未使用或指定,版本没有类型名称 G?

所以结果看起来像:

unicorn <double, int>;

class unicorn {
double value01;
int value02;
};

并且没有参数或指定的类型名 G

unicorn <double>

class unicorn {
T value01;
// "not included in this instance"
};

最佳答案

如果您的用例数量有限并且不想深入研究模板元编程,那么您可以简单地进行模板特化

#include <iostream>
using namespace std;

template <typename... Args>
struct Something;

template <typename T>
struct Something<T> {
T a;
};

template <typename T, typename U>
struct Something<T, U> {
T a;
U b;
};

int main() {
__attribute__((unused)) Something<int> a;
__attribute__((unused)) Something<int, double> b;

return 0;
}

但对于一般情况,我认为 std::tuple可能会在这里起作用。看看下面的代码

#include <tuple>
#include <iostream>
using namespace std;

template <typename... Args>
class Something {
std::tuple<Args...> tup;
};

int main() {
__attribute__((unused)) Something<int> a;
__attribute__((unused)) Something<int, double> b;

return 0;
}

当然你应该知道一些事情,比如std::refget<>元组函数。您还可以使用一些模板元编程访问模板包的类型。我不会在这里解释,因为它可能会变成一个真的 很长的答案,否则,如果您仍然希望我这样做,请在下面的评论中告诉我,我会尽力向您解释。

关于c++ - 可变参数模板且没有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38083957/

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