是否可以在可变参数函数模板中使用“ enable_if”和“ is_same”? [英] Is it possible to use 'enable_if' and 'is_same' with variadic function templates?

查看:175
本文介绍了是否可以在可变参数函数模板中使用“ enable_if”和“ is_same”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个非变量函数模板可以编译:

These two non-variadic function templates do compile:

template <typename T, typename U>
typename std::enable_if<std::is_same<U, int>::value, void>::
type testFunction(T a, U b) {
    std::cout << "b is integer\n";
}

template <typename T, typename U>
typename std::enable_if<std::is_same<U, float>::value, void>::
type testFunction(T a, U b) {
    std::cout << "b is float\n";
}

但是,类似的可变参数模板无法编译:

however, similar variadic templates do not compile:

template <typename T, typename... U>
typename std::enable_if<std::is_same<U, int>::value, void>::
type testFunction(T a, U... bs) {
    std::cout << "bs are integers\n";
}

template <typename T, typename... U>
typename std::enable_if<std::is_same<U, float>::value, void>::
type testFunction(T a, U... bs) {
    std::cout << "bs are floats\n";
}

也许我正在尝试做一些无法完成的事情。我知道可以使用初始化程序列表实现类似的功能,但我想避免使用初始化程序列表参数所需的大括号。

Maybe I am trying to do something that cannot be done. I know that similar functionality can be achieved using initializer lists, but I would like to avoid curly brackets required for initializer list arguments.

推荐答案

折叠表达式 17:

template <typename T, typename... U>
typename std::enable_if<(std::is_same<U, float>::value && ...), void>::
type testFunction(T a, U... bs) {
    std::cout << "bs are floats\n";
}

在C ++ 11中,您可以重新实现 std :: conjunction

In C++11, you can reimplement std::conjunction:

template<class...> struct conjunction : std::true_type { };
template<class B1> struct conjunction<B1> : B1 { };
template<class B1, class... Bn>
struct conjunction<B1, Bn...> 
    : std::conditional_t<bool(B1::value), conjunction<Bn...>, B1> {};

template <typename T, typename... U>
typename std::enable_if<
    std::conjunction_v<std::is_same<U, float>...>, 
    void
>::type testFunction(T a, U... bs) {
    std::cout << "bs are floats\n";
}

这篇关于是否可以在可变参数函数模板中使用“ enable_if”和“ is_same”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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