代码之家  ›  专栏  ›  技术社区  ›  user3749332

模板专用化-模板参数太少[closed]

  •  1
  • user3749332  · 技术社区  · 10 年前

    所以我在玩模板专业化,遇到了一个问题。我在看 this 同时编写以下代码。

    我减少了它,但基本上我对calc的模板做了一些不正确的事情,我不确定是什么。在所有其他帖子中,我都看到人们在专业课之前忘记了“模板”,但我不认为这是导致我问题的原因。有什么建议吗?

    #include <type_traits>
    #include <iostream>
    
    template <typename T, bool isDouble = std::is_same<T, double>::value>
    struct precision
    { 
        typedef T p_type;
        /* some stuff here*/
    };
    
    template <typename T>
    struct precision<T, false>
    { 
        typedef T p_type;
        /* some stuff here*/
    };
    
    template <typename P>
    struct is_double
    { 
        static const bool value = std::is_same< typename P::p_type, double >::value;
    };
    
    template <typename T, typename SP, typename DP>
    struct calc
    {
        static_assert(!is_double<SP>::value, "SP is not single precision");
        static_assert(is_double<DP>::value, "DP is not double precision");
    };
    
    template <typename T, typename SP>
    struct calc<T, SP, precision<double>>
    {
        static_assert(!is_double<SP>::value, "SP is not single precision");
    };
    
    template <typename T, typename DP>
    struct calc<T, precision<float>, DP>
    {
        static_assert(is_double<DP>::value, "DP is not double precision");
    };
    
    template <typename T>
    struct calc<T, precision<float>, precision<double>>
    { };
    
    int main()
    {
        calc<int> t1; //"too few template arguments"
        calc<int, precision<double> > t2; //"too few template arguments"
        calc<int, precision<float> > t3; //"too few template arguments"
        calc<int, precision<float>, precision<double>> t4;
    }
    
    2 回复  |  直到 10 年前
        1
  •  1
  •   Daniel Frey    10 年前

    您正在为实现提供专门化,但您似乎希望这也为主模板的模板参数提供默认值。这不是真的。

    要提供默认值,请尝试:

    template <typename T, typename SP = precision<float>, typename DP = precision<double>>
    struct calc
    {
        static_assert(!is_double<SP>::value, "SP is not single precision");
        static_assert(is_double<DP>::value, "DP is not double precision");
    };
    

    让代码的其余部分(包括专门化)保持原样。查看代码的哪些部分将以何种方式对更改做出反应,但请注意,这并不能解决所有问题。它只是为了帮助你理解你在混淆两种不同的东西。

        2
  •  1
  •   Logicrat    10 年前

    您已经为定义了模板 calc 具有3个参数,但没有将所有这些参数用于 main() .