简体   繁体   English

如何在 C++ 中专门化一个可变参数模板函数?

[英]How to specialize a variadic template function in c++?

Let the function foo be given with the following "signature":让函数 foo 带有以下“签名”:

template<typename ...Ts>
void foo(Ts ...args)

This is a bit overdone since I need foo to proccess double s only.这有点过头了,因为我只需要 foo 来处理double s。 How can I modify foo so it accepts double s only?如何修改 foo 使其仅接受double s?

The original code has been Godbolted:原始代码已被Godbolted:

#include <tuple>
#include <iostream>

template<typename ...Ts>
void foo(Ts ...args)
{
    std::tuple<Ts...> tu(args...);
    std::apply([](Ts const&... tupleArgs)
        {
            ((std::cout << tupleArgs << " "), ...);
        }, tu);
}

int main()
{
    foo(-2.44, -5.66, 78.99);
}

The output reads:输出如下:

-2.44 -5.66 78.99 -2.44 -5.66 78.99

You can constrain your template like this:你可以像这样约束你的模板:

template<typename ...Ts>
requires std::conjunction_v<std::is_same<double, Ts>...>
void foo(Ts ...args)
{
  // ...
}

Here's a demo这是一个演示

As pointed out by HolyBlackCat, you can write the template much more conveniently like this:正如 HolyBlackCat 所指出的,您可以像这样更方便地编写模板:

void foo(std::same_as<double> auto ...args)
{
    (std::cout << ... << args);
}

Note also that you can use a fold expression to print the arguments.另请注意,您可以使用折叠表达式来打印参数。

Here's a demo .这是一个演示

Those of us who are still stuck with C++17 will have to do with a slightly uglier syntax :(我们这些仍然坚持使用 C++17 的人将不得不使用稍微丑陋的语法:(

template<typename ...Ts>
std::enable_if_t<std::conjunction_v<std::is_same<Ts, double>...>> foo(Ts ...args)
{
    (std::cout << ... << args);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM