c++ - 类型限制的可变参数模板函数

标签 c++ c++14 variadic-templates variadic-functions

我可以编写以下代码来定义带有任意数量参数的函数:

template <typename... Arguments>
void f(Arguments... sums) {
    // Do something.
}

然后这样调用它

f(1, 2, 3, 4);

但是我如何将所有参数限制为例如整数?

最佳答案

使用 this SO answer 中的 all_true您可以使用以下内容:

#include <type_traits>

template <bool...> struct bool_pack;

template <bool... v>
using all_true = std::is_same<bool_pack<true, v...>, bool_pack<v..., true>>;

template<typename... Args,
         typename = std::enable_if_t<all_true<std::is_same<int, Args>{}...>{}>>
void f(Args... sums)
{
    // Do something.
}

int main()
{
    f(1, 2, 3, 4);
    f(1.1, 2, 3, 4); // compile error
}

live example

关于c++ - 类型限制的可变参数模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34842346/

相关文章:

c++ - 是否可以计算任意 std::regex 对象中捕获组的数量?

c++ - boost::any 库不编译: "Array used as initializer"错误

c++ - 编译时素数列表 : specialization error

c++ - 如何用强盗转换这个类型列表?

c++ - 是不是捕获了异常未定义的行为?

c++ - 关于c++类的疑惑

c++ - 为什么 std::map 在按值传递给 lambda 时表现异常?

c++ - 如何在 CBitmap 上使用透明背景的 CDC 绘制文本?

c++ - 为什么 std::enable_if 需要第二种模板类型?

C++ Variadic Vector 运算符实现