【问题标题】:Variadic template with SFINAE带有 SFINAE 的可变参数模板
【发布时间】:2017-07-13 09:06:47
【问题描述】:
template<class T> struct is_vector : public std::false_type {};

template<class T, class Alloc>
struct is_vector<std::vector<T, Alloc>> : public std::true_type {};

template<typename T>
template<typename... Ys, typename = typename std::enable_if<is_vector<std::decay_t<Ys...>>::value>::type>
void A<T>::function(Ys &&... y){}

对于一个向量工作正常(没有可变参数模板的版本),但如果我尝试为可变参数模板做......它不起作用,我怎样才能为可变参数模板做好 SFINAE。有人可以解释一下为什么这不适用于可变参数模板以及我必须改进的地方。

【问题讨论】:

  • 您的意思可能是std::decay_t&lt;Ys&gt;...,但即使您修复它也会失败,因为is_vector 不是可变参数。

标签: c++ variadic-templates sfinae


【解决方案1】:

您无法检查未展开的包是否为向量。您必须检查包中的每个元素。您使用std::decay_t 表示您使用的是C++17,所以我假设您可以使用折叠表达式。

#include <iostream>
#include <type_traits>
#include <vector>

template<class T> struct is_vector : public std::false_type {};

template<class T, class Alloc>
struct is_vector<std::vector<T, Alloc>> : public std::true_type {};

template<typename... Ys, typename = typename std::enable_if< (... && is_vector< std::decay_t<Ys> >::value) >::type >
void function(Ys&&...) { std::cout << __PRETTY_FUNCTION__ << '\n'; }

struct A {};

int main()
{
  std::vector<int> vi;
  std::vector<double> vd;
  std::vector<A> va;
  function(vi, vd, va);
}

在 C++17 之前,您需要一个小助手结构,我称之为 all

#include <iostream>
#include <type_traits>
#include <vector>

template < bool... > struct all;
template < > struct all<> : std::true_type {};
template < bool B, bool... Rest > struct all<B,Rest...>
{
  constexpr static bool value = B && all<Rest...>::value;
};

template<class T> struct is_vector : public std::false_type {};

template<class T, class Alloc>
struct is_vector<std::vector<T, Alloc>> : public std::true_type {};

template<typename... Ys, typename = typename std::enable_if< all< is_vector< std::decay_t<Ys> >::value... >::value >::type >
void function(Ys&&...) { std::cout << __PRETTY_FUNCTION__ << '\n'; }

struct A {};

int main()
{
  std::vector<int> vi;
  std::vector<double> vd;
  std::vector<A> va;
  function(vi, vd, va);
}

【讨论】:

  • 谢谢,现在我理解了 C++17 之前的解决方案,之前我看到了这个,但是我理解有问题。
猜你喜欢
  • 2015-12-14
  • 1970-01-01
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 2012-01-20
  • 2013-04-17
相关资源
最近更新 更多