所以我有这个结构:
template <typename T>
struct _vect2 {
T x;
T y;
_vect2(T x, T y) : x(x), y(y) { }
_vect2() { }
};
我想创建一个函数,该函数采用“无限”数量的这些结构。
template <typename T, _vect2<T>... Args>
double vect_distance(Args... arguments) {}
它应该如何工作:
struct vect_2i : public _vect2<int> {
vect_2i() : _vect2() { }
vect_2i(int x, int y) : _vect2(x, y) { }
};
vect_2i vect1, vect2;
auto distance = vect_distance(vect1, vect2);
使用此代码,我收到语法错误,但不知道为什么。采取论据的正确方法是什么?
最佳答案
您可以推导出第一个参数的类型,并强制其他参数派生自/成为相同推导的 vector T
类型。
在 c++20 :
#include <concepts>
template <typename T>
double vect_distance(const vect2<T>& head,
const std::derived_from<vect2<T>> auto&... tail);
在 c++17 :
#include <type_traits>
template <typename T, typename... Ts>
auto vect_distance(const vect2<T>& head, const Ts&... tail)
-> std::enable_if_t<(std::is_base_of<vect2<T>, Ts>{} && ...), double>;
在 c++14 :
#include <type_traits>
template <bool...>
struct bool_pack {};
template <typename T, typename... Ts>
auto vect_distance(const vect2<T>& head, const Ts&... tail)
-> std::enable_if_t<std::is_same<bool_pack<true, std::is_base_of<vect2<T>, Ts>{}...>,
bool_pack<std::is_base_of<vect2<T>, Ts>{}..., true>
>{}, double>;
关于带有 "infinite"参数的 c++ 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62393834/