简体   繁体   English

C++ 模板定义 function 的参数个数

[英]C++ template defining number of parameters of function

Lets say i have a class looking like this可以说我有一个 class 看起来像这样

template<int n>
class A{
   array<size_t, n> sizes;
   //...
public:
   template <int k>
   A<k> reshape(array<size_t, k> new_sizes){
      return A<k>(new_sizes):
   }
};

it works but the parameter new_sizes is syntatically suboptimal, since i have to call it like that:它有效,但参数new_sizes在语法上是次优的,因为我必须这样称呼它:

foo.reshape(array<size_t, 3>{1,2,3});

This does not work:这不起作用:

foo.reshape({1,2,3});

Is there a way to either define a initializer_list with compile time size (so i could use it instead of the array) OR (even better) a way to define the size of a variadic parameter, so i could write something like有没有一种方法可以定义一个具有编译时大小的initializer_list (这样我就可以使用它而不是数组)或者(甚至更好)一种定义可变参数大小的方法,这样我就可以编写类似

foo.reshape(1,2,3);

OR (even better) a way to define the size of a variadic parameter, so i could write something like foo.reshape(1,2,3);或者(甚至更好)一种定义可变参数大小的方法,所以我可以写类似foo.reshape(1,2,3);

You could take the sizeof... a parameter pack:您可以采用sizeof...参数包:

template <size_t N>
class A {
    std::array<size_t, N> sizes;

public:
    A() = default;

    template <class... Args>
    A(Args&&... ss) : sizes{static_cast<size_t>(ss)...} {}

    template <class... Args>
    A<sizeof...(Args)> reshape(Args&&... new_sizes) {
//    ^^^^^^^^^^^^^^^
        return A<sizeof...(Args)>(static_cast<size_t>(new_sizes)...);
    }
};

// deduction guide:
template <class... Args>
A(Args&&...) -> A<sizeof...(Args)>;

Demo演示

{1, 2, 3} has no type but can be deduced as initializer_list<T> or T[N] {1, 2, 3}没有类型但可以推断为initializer_list<T>T[N]

So to keep your syntax, it would be:所以为了保持你的语法,它将是:

template <std::size_t K>
A<K> reshape(/*const*/ size_t (&new_sizes)[K])
{
    return A<K>(new_sizes):
}

so i could write something like foo.reshape(1,2,3);所以我可以写类似foo.reshape(1,2,3);东西

For that variadic template:对于那个可变参数模板:

template <typename... Ts>
A<sizeof...Ts> reshape(Ts... elems)
{
    return reshape({elems...}); // using above method
}

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

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