C ++ 17中的部分类模板参数推导 [英] Partial class template argument deduction in C++17

查看:72
本文介绍了C ++ 17中的部分类模板参数推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,我们使用C ++ 17功能类模板参数推导来推断 val 的类型为 Base< int,double,bool>

In the example below, we use the C++17 feature "Class template argument deduction" to deduce that val is of type Base<int, double, bool>:

template<class T, class U, class V>
struct Base {
    Base(T, U) { };
    Base(T, U, V) { };
    Base(V) { };
};

void func() {
    Base val(1, 4., false);
}

现在,是否可以部分指定模板参数,让其余的参数推论出来的?实际上,类似

Now, is it possible to partially specify the template arguments, and let the remaining ones be deduced? Effectively something like this:

Base<V = bool> val1(1, 4.);        // U & V deduced --> Base<int, double, bool>
Base<T = bool, T = int> val2(5.);  // V deduced     --> Base<bool, int, double>

我尝试过例如

template<class T, class U> using Base2 = Base<T, U, double>;

void func() {
    NewBase2 val(1, 2);
}

但它不能编译:'Base2' :使用别名模板需要模板参数列表

以某种方式可以部分扣除吗?如果不可能直接解决,有什么好的解决方法?

Is partial deduction possible somehow? If it is not possible directly, are there any good workarounds?

推荐答案

您可以添加以下推导指南:

You might add deduction guide as follow:

template<class T, class U, class V>
Base(T, U) -> Base<T, U, bool>;

template<class V>
Base(V) -> Base<bool, int, V>;

这允许

Base val1(1, 4.); // Base<int, double, bool>
Base val2(5.);    // Base<bool, int, double>

如果要指定默认模板,则可以对<$ c使用旧方法$ c> make _

If you want to specify the "default" template, you might use the old way with make_

template <typename V, typename T, typename U>
Base<T, U, V> make_Base(T t, U u)
{
    return Base<T, U, V>{t, u};
}

template <typename T, typename U, typename V>
Base<T, U, V> make_Base(V v)
{
    return Base<T, U, V>{v};
}


auto val1 = make_Base<bool>(1, 4.);   // Base<int, double, bool>
auto val2 = make_Base<bool, int>(5.); // Base<bool, int, double>

这篇关于C ++ 17中的部分类模板参数推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆