模板非常适合对模板函数和类进行编程,因此我们可以使用它来缩短代码并让编译器为我们做一些工作。
就我而言,我想利用模板类。
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::ref
和get<>
函数。您还可以使用一些模板元编程来访问模板包的类型。我在这里不做解释,因为它可能会成为或长答案,否则,如果您仍然希望我这样做,请在下面的评论中告诉我,我将尝试向您解释。