我有以下代码:
#include <tuple>
#include <utility>
#include <iostream>
template<class T>
struct e {
};
template <>
struct e<int N> {
static const int value = N;
};
int main() {
std::cout << e<5>::value << std::endl;
}
这给了我一个类型不匹配。我意识到 5 是一个 r 值,所以我猜我的解决方案可能看起来像
e<int &&N>
但这也行不通。我该怎么做才能普遍实现这一点?我也在使用术语 right callint <int N>
类型模板参数,其中 <typename/class T>
是非类型模板参数吗?
最佳答案
您已经为主模板指定了一个类型名称,然后您不能专门处理一个 int 的值。您的主要模板必须是
template <int N>
struct e
{ static const int value = N; };
然后您将专注于特定值。当然,对于您的示例,假设您只使用 int
值 instaciante,上面的模板就是所需要的,根本不需要专门化。
但是,假设可以使用其他类型,您可以部分专注于 std::integral_constant
或类似的东西,这样您就可以专注于一个类型(包装 int 值)。
有点像,
#include <iostream>
#include <type_traits>
template<class T>
struct e {
};
template <int N>
struct e<std::integral_constant<int,N> > {
static const int value = N;
};
int main() {
std::cout << e<std::integral_constant<int,5>>::value << std::endl;
}
关于c++ - 如何进行模板类型参数特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51047821/