模板化失败,出现编译错误错误:模板参数数量错误(2,应该是3)

Templated if fails with compiler error error: wrong number of template arguments (2, should be 3)

本文关键字:错误 失败 参数 编译 数数      更新时间:2023-10-16

如果我用gcc

编译以下代码
namespace TMP {
    // template to choose type depending on boolean condition
    template <bool condition, typename x, typename y> struct if_t                               { typedef y type; };
    template <                typename x, typename y> struct if_t<true, typename x, typename y> { typedef x type; };
}
TMP::if_t<false, uint8_t, uint16_t>::type test;

我得到一个错误信息

error: wrong number of template arguments (2, should be 3)

如果我删除第二个模板,它将成功编译。然而,我认为我的代码几乎是相同的书wikibook的例子。我错在哪里?

实际上,只是删除多余的typename。使用GCC 4.9.2编译

namespace TMP {
    // template to choose type depending on boolean condition
    template <bool condition, typename x, typename y>
    struct if_t
    {
        typedef y type;
    };
    template <typename x, typename y>
    struct if_t < true, x, y >
    {
        typedef x type;
    };
}

在yufeng的帮助下,我发现了应该怎么做:

namespace TMP {
    // template to choose type depending on boolean condition
    template <bool condition, typename x, typename y> 
        struct if_t { typedef y type; };
    template <typename x, typename y> 
        struct if_t<true, typename x, typename y> { typedef x type; };
}
TMP::if_t<false, uint8_t, uint16_t>::type test;
相关文章: