带有默认值的C++可变参数模板函数参数

cfa*_*771 18 c++ default-value variadic-functions variadic-templates c++11

我有一个函数,它带有一个默认值的参数.现在我还希望它采用可变数量的参数并将它们转发给其他函数.默认值的函数参数必须是最后一个,所以...我可以将该参数放在可变参数包之后,编译器会在调用函数时检测我是否提供它吗?

(假设包不包含最后一个参数的类型.如果需要,我们可以假设,因为这种类型一般不应该被称为给用户,否则它反正认为我的接口错误使用.. ..)

template <class... Args>
void func (Args&&... args, SomeSpecialType num = fromNum(5))
{
}
Run Code Online (Sandbox Code Playgroud)

Yak*_*ont 17

不,包必须是最后的.

但你可以假装它.您可以检测包中的最后一个类型.如果是SomeSpecialType,你可以运行你的功能.如果不是SomeSpecialType,您可以使用转发和fromNum(5)附加的参数递归调用自己.

如果您想要花哨,可以使用SFINAE技术在编译时(即,不同的重载)完成此检查.但是,这可能是不值得冒这个险,考虑到"运行时"检查将在一个给定的过载不变,因此几乎肯定会被优化掉了,而SFINAE不应该轻易使用.

这不会为您提供所需的签名,但它会为您提供所需的行为.您必须在评论中解释预期的签名.

在删除拼写错误之后,这样的事情:

// extract the last type in a pack.  The last type in a pack with no elements is
// not a type:
template<typename... Ts>
struct last_type {};
template<typename T0>
struct last_type<T0> {
  typedef T0 type;
};
template<typename T0, typename T1, typename... Ts>
struct last_type<T0, T1, Ts...>:last_type<T1, Ts...> {};

// using aliases, because typename spam sucks:
template<typename Ts...>
using LastType = typename last_type<Ts...>::type;
template<bool b, typename T=void>
using EnableIf = typename std::enable_if<b, T>::type;
template<typename T>
using Decay = typename std::decay<T>::type;

// the case where the last argument is SomeSpecialType:
template<
  typename... Args,
  typename=EnableIf<
    std::is_same<
      Decay<LastType<Args...>>,
      SomeSpecialType
    >::value
  >
void func( Args&&... args ) {
  // code
}

// the case where there is no SomeSpecialType last:    
template<
  typename... Args,
  typename=EnableIf<
    !std::is_same<
      typename std::decay<LastType<Args...>>::type,
      SomeSpecialType
    >::value
  >
void func( Args&&... args ) {
  func( std::forward<Args>(args)..., std::move(static_cast<SomeSpecialType>(fromNum(5))) );
}

// the 0-arg case, because both of the above require that there be an actual
// last type:
void func() {
  func( std::move(static_cast<SomeSpecialType>(fromNum(5))) );
}
Run Code Online (Sandbox Code Playgroud)

或类似的东西.


Mar*_*k R 8

从 C++17 开始,有一种方法可以通过使用类模板参数推导用户定义的推导指南来解决此限制。

这对于 C++20 std::source_location特别有用。

这是 C++17 演示:

#include <iostream>

int defaultValueGenerator()
{
    static int c = 0;
    return ++c;
}

template <typename... Ts>
struct debug
{    
    debug(Ts&&... ts, int c = defaultValueGenerator())
    {
        std::cout << c << " : ";
        ((std::cout << std::forward<Ts>(ts) << " "), ...);
        std::cout << std::endl;
    }
};

template <typename... Ts>
debug(Ts&&...args) -> debug<Ts...>;

void test()
{
    debug();
    debug(9);
    debug<>(9);
}

int main()
{
    debug(5, 'A', 3.14f, "foo");
    test();
    debug("bar", 123, 2.72);
}
Run Code Online (Sandbox Code Playgroud)

现场演示

使用 source_location 的演示(应该从 C++20 开始可用,但对于编译器来说仍然是实验性的)。


xav*_*urs 5

另一种方法是通过元组传递可变参数。

template <class... Args>
void func (std::tuple<Args...> t, SomeSpecialType num = fromNum(5))
{
  // don't forget to move t when you use it for the last time
}
Run Code Online (Sandbox Code Playgroud)

优点:接口要简单得多,重载和添加默认值的参数非常容易。

缺点:调用者必须手动将参数包装在std::make_tuplestd::forward_as_tuple调用中。同样,您可能必须借助std::index_sequence技巧来实现该功能。

  • 另一种类似的方法是 `template&lt;class...Args&gt; auto func( Args&amp;&amp;... args ) { return [&amp;]( SomeSpecialType num = fromNum(5) ) { /* code */ }; }`,称为“func(first,argument,here)(extra_Optional_argument)”。 (2认同)