dre*_*iti 7 c++ templates dynamic-programming variadic-functions
模板适用于编程模板函数和类,因此我们可以使用缩短代码并让编译器为我们做一些工作.
在我的情况下,我想使用模板类,例如.
template <typename T, typename G> class unicorn {
T value01;
G value02; <- not used in ever instance of class unicorn
};
Run Code Online (Sandbox Code Playgroud)
有没有办法,编译器使用typename T = int创建一个实例,如果没有使用或指定,没有 typename G的版本?
所以结果如下:
unicorn <double, int>;
class unicorn {
double value01;
int value02;
};
Run Code Online (Sandbox Code Playgroud)
并且没有Argument或指定的typename G.
unicorn <double>
class unicorn {
T value01;
// "not included in this instance"
};
Run Code Online (Sandbox Code Playgroud)
如果您有一定数量的用例并且不想深入了解深层模板元编程,那么您可以简单地进行模板专业化
#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;
}
Run Code Online (Sandbox Code Playgroud)
但对于一般情况,我认为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;
}
Run Code Online (Sandbox Code Playgroud)
当然你应该知道一些像std::ref和get<>元组的功能.您还可以使用某些模板元编程来访问模板包的类型.我不是在这里解释,因为它可能会成为一个非常长的答案,如果你仍然希望我这样做,请在下面的评论中告诉我,我会尽力向你解释.
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |