【问题标题】:Template argument deduction/substitution failed with Boost Hana type_cBoost Hana type_c 模板参数扣除/替换失败
【发布时间】:2022-01-12 19:39:37
【问题描述】:

我不明白为什么下面这个简单的例子会失败:

#include <boost/hana.hpp>

template <typename _T>
static constexpr void Foo(boost::hana::type<_T>) {
}

int main() {
    Foo(boost::hana::type_c<int>);
    return 0;
}

我收到以下错误消息:

[build] error: no matching function for call to ‘Foo(boost::hana::type<int>&)’
[build]    74 |     Foo(hana::type_c<int>);
[build]       |     ~~~^~~~~~~~~~~~~~~~~~~
[build] note: candidate: ‘template<class _T> constexpr void Morphy::Foo(boost::hana::type<T>)’
[build]    61 | static constexpr void Foo(hana::type<_T>) {
[build]       |                       ^~~
[build] note:   template argument deduction/substitution failed:
[build] note:   couldn’t deduce template parameter ‘_T’
[build]    74 |     Foo(hana::type_c<int>);
[build]       |     ~~~^~~~~~~~~~~~~~~~~~~

实现上述工作的唯一方法是通过编写 Foo&lt;int&gt;(boost::hana::type_c&lt;int&gt;) 来明确 Foo 的模板参数。 为什么编译器无法自动推导出模板参数?

请注意,如果我在 Foo 的声明中使用 boost::hana::basic_type 代替 boost::hana::type,则上述代码有效。 这种替代方法是否正确?

【问题讨论】:

    标签: c++ templates boost template-meta-programming template-argument-deduction


    【解决方案1】:

    type_c&lt;int&gt; 是一个变量模板,它创建一个type&lt;int&gt; 类型的值。当传递type&lt;int&gt; 时,似乎Foo 应该很容易从type&lt;_T&gt; 推导出参数_T。但是这是不可能的,因为type 是一个别名模板,它引用了某个辅助类的成员,并且它的参数总是在非推导上下文中。

    template< typename x_Type >
    struct FooImpl
    {
        using Type = x_Type;
    };
    
    template< typename x_Type >
    using Foo = typename FooImpl<x_Type>::Type;
    
    template< typename x_Type > // x_Type can not be deduced
    void Bar(Foo<x_Type>) {}
    
    int main()
    {
        Bar(Foo<int>{});
        return 0;
    }
    

    online compiler

    basic_type 有效,因为它是type_c 的实际类型。

    【讨论】:

    猜你喜欢
    • 2013-06-20
    • 2019-09-11
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    相关资源
    最近更新 更多