我可以创建一个只接受指针的可变模板:
template<typename ... Types>
void F(Types *... args);或只接受引用的可变模板:
template<typename ... Types>
void F(Types &... args);如何创建接受非const引用或指针的模板?
例如。
int a, b, c;
F(a, &b); // => F<int &, int *>
F(a, 3); // Error, 3 not pointer and cannot bind to non const-reference注意:参考版本可能看起来不错,因为它可以绑定到指针引用,但它不会绑定到int * const。
发布于 2015-08-28 09:35:27
您可以简单地检查Args中每种类型的需求--例如:
// Helper templates
template <bool...> struct bool_pack {};
template <bool b, bool... rest>
struct all_of : std::is_same<bool_pack<b, rest...>, bool_pack<rest..., b>> {};
template <typename... Args>
auto F(Args&&... args)
-> std::enable_if_t<all_of<std::is_lvalue_reference<Args>{}
or std::is_pointer<std::decay_t<Args>>{}...>{}>
{}假设F仅与演绎一起使用,则只允许使用lvalue和指针。Demo与您的示例。
https://stackoverflow.com/questions/32267516
复制相似问题