c++ - 如何进行模板类型参数特化?

标签 c++ templates metaprogramming template-meta-programming

我有以下代码:

#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;
}

Demo

关于c++ - 如何进行模板类型参数特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51047821/

相关文章:

c++ - 更多与eclipse cdt

c++ - 是否有任何理由在预分配内存中的 POD 结构上调用 new?

JavaScript 正则表达式模板 : only match when string inside brackets is equal

F# 函数调用依赖关系图

python - 以编程方式检测 RDBMS 中多对多关系的方法有哪些?

c++ - 在设置函数指针之前绑定(bind)参数?

c++ - 使用 constexpr 编译时间哈希

c++ - 这篇 cppreference.com 文章的结尾有问题

c++ - 表达模板化负数字文字的首选方式

Javascript 更改函数参数