代码之家  ›  专栏  ›  技术社区  ›  Dr.Knowitall

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

  •  0
  • Dr.Knowitall  · 技术社区  · 7 年前

    我有以下代码:

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

    <int N> 类型化模板参数,其中 <typename/class T> 是非类型模板参数吗?

    1 回复  |  直到 7 年前
        1
  •  4
  •   rmawatson    7 年前

    您已经为主模板指定了一个类型名,然后不能专门化int的值。

    template <int N> 
    struct e
    { static const int value = N; };
    

    然后你会专门研究特定的值。当然,以你为例,假设你只与 int 值,上面的模板就是所需的全部,而且根本没有专门化。

    但是,假设可以使用其他类型,您可以部分地专门化 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