c++ 将参数约束到模板类的内部类型

quhf5bfb  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(81)

我想有一个概念,它限制了模板(例如std::vector<...>::iterator)的嵌套类的类型。我不能改变模板及其嵌套类。

template<class T>
struct A
{
  struct B {};
};

template<class T>
concept is_B = requires(T x) { []<class U>(typename A<U>::B){}(x); };

void foo(is_B auto) {};

void bar()
{
  foo(A<int>::B{});  // should compile
  foo(int{});        // should not compile
}

字符串
上面的代码不起作用,因为U不能被推导出来(这有点像关于嵌套类的模板参数推导的臭名昭著的问题)。
有没有办法写出这样的概念?

oyxsuwqo

oyxsuwqo1#

你可以用一个类型trait来强制它,这个trait被专门化为对于一组特定的类型为true,否则为false。

template<class> struct is_legal : std::false_type {};
template<> struct is_legal<typename std::vector<int>::iterator> : std::true_type {};
// more of previous line
template<class T> concept my_concept = (is_legal<T>::value);

字符串
这可以用一个宏来缩短:

#define IS_TRUE(t) template<> struct is_legal<t> : std::true_type {};
IS_TRUE(typename std::vector<int>::const_iterator)

相关问题