如何进行模板化类型参数专业化?

How do I do templated typed parameter specialization?

我有以下代码:

#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