是否可以定义一个指向具有 "not" 可变参数列表的函数的指针,例如 "bools"?
Is possible define a pointer to a function which has "not" variable argument list e.g "bools"?
我知道我可以在 C++ 中创建指向具有可变参数列表的函数的指针:
bool (*fun)(bool,...);
但我正在寻找可以使指向以下任何函数的指针:
bool f(bool);
bool f(bool, bool);
bool f(bool, bool, bool);
bool f(bool, bool, bool, bool);
bool f(bool, bool, bool, bool /*etc. */);
现在我尝试通过指向函数的指针来解决这个问题,该函数获取布尔数组和数组大小
bool (*f)(bool*, in);
但我不能确定传递的数组至少是 size 参数中的大小。
有多种解决方法:
传递对数组的引用并根据大小对其进行模板化。这样,您可以避免数组到指针的衰减并且不会丢失任何类型信息:
template <size_t N> bool func(bool(*f)(bool(&arr)[N]));
使用std::array
得到一个有值语义的数组:
template <size_t N> bool func(bool(*f)(std::array<bool, N>));
使用可变模板允许旧签名。这可能有点矫枉过正。
template <typename ... Args, typename = std::enable_if_t<AllSame<bool, Args...>::value>>
bool func(bool(*f)(Args...));
template <typename T, typename ... Args>
struct AllSame;
template <typename T>
struct AllSame<T> : public std::true_type{};
template <typename T, typename Arg, typename ... Args>
struct AllSame : public std::conditional_t<std::is_same<T, Arg>::value,
AllSame<T, Args...>,
std::false_type> {};
我知道我可以在 C++ 中创建指向具有可变参数列表的函数的指针:
bool (*fun)(bool,...);
但我正在寻找可以使指向以下任何函数的指针:
bool f(bool);
bool f(bool, bool);
bool f(bool, bool, bool);
bool f(bool, bool, bool, bool);
bool f(bool, bool, bool, bool /*etc. */);
现在我尝试通过指向函数的指针来解决这个问题,该函数获取布尔数组和数组大小
bool (*f)(bool*, in);
但我不能确定传递的数组至少是 size 参数中的大小。
有多种解决方法:
传递对数组的引用并根据大小对其进行模板化。这样,您可以避免数组到指针的衰减并且不会丢失任何类型信息:
template <size_t N> bool func(bool(*f)(bool(&arr)[N]));
使用
std::array
得到一个有值语义的数组:template <size_t N> bool func(bool(*f)(std::array<bool, N>));
使用可变模板允许旧签名。这可能有点矫枉过正。
template <typename ... Args, typename = std::enable_if_t<AllSame<bool, Args...>::value>> bool func(bool(*f)(Args...)); template <typename T, typename ... Args> struct AllSame; template <typename T> struct AllSame<T> : public std::true_type{}; template <typename T, typename Arg, typename ... Args> struct AllSame : public std::conditional_t<std::is_same<T, Arg>::value, AllSame<T, Args...>, std::false_type> {};