【问题标题】:Is there a way to deduce alias templates to template template parameter while still preserving its property of being deduced context有没有办法将别名模板推断为模板模板参数,同时仍保留其被推断上下文的属性
【发布时间】:2017-10-08 11:58:02
【问题描述】:

一段时间后,我再次发现了模板 template-parameters 的强大功能。参见例如以下sn-p:

template <template <class> class TT, class T>
void foo(TT<T>) {
}

template <class T>
using typer = T;

int main() {
    foo<typer>(int{});
}

别名模板作为模板传递给模板template-parameter,并用于进一步检测模板的其他参数,因为它是推断的上下文。美女!

但是,当需要推断别名模板本身时,编译器似乎变得疯狂:

template <template <class> class>
struct tag{};

template <template <class> class TT, class T>
void foo(tag<TT>, TT<T>) {
}

template <class T>
using typer = T;

int main() {
    foo(tag<typer>{}, int{});
}

[live demo]

编译器当然是对的,因为tag&lt;TT&gt;fooTT&lt;T&gt; 参数都可以推导出TT,并且int{} 与模板模板不匹配类型参数模式。有什么办法可以保留T 的推导上下文,但在TT&lt;T&gt; 中使TT 非推导上下文?

附:我的意图很纯粹,这只是一个理论问题,背后没有任何问题。

【问题讨论】:

  • 老实说,我看不出第一次 beautifulness 和第二次尝试有什么用处。无论如何,这个问题很有趣,+1。
  • @skypjack 正如我所说的,我什至没有考虑过可能的用法,所以你可能是对的,没有...

标签: c++ templates template-templates template-aliases


【解决方案1】:

我认为这样写会更容易/更清晰:

template <template <class> class TT, class T>
void foo(tag<TT>, T, std::enable_if_t< std::is_same<T,TT<T>>::value >* = 0 )

或限制较少的

template <template <class> class TT, class T>
void foo_impl( tag<TT>, TT<T> ){}

template <template <class> class TT, class T>
void foo( tag<TT> a, T b ){ foo_impl<TT>( a, b ); }

作为旁注,这表明标准中的(非规范性)注释声称​​别名模板名称永远不会被推断有点不准确......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2012-09-15
    • 2013-02-18
    • 1970-01-01
    • 2023-03-31
    • 2010-12-22
    相关资源
    最近更新 更多