22

我正在阅读这篇文章并试图了解N3601是关于什么的。它说这个成语在网络搜索中出现了很多,但我找不到任何东西。是什么

template<typename T, T t>

成语,它解决了什么问题,它是如何使用的,什么是隐式模板参数,以及该提案旨在解决什么问题?

4

2 回答 2

15

正在解决的问题是从模板非类型参数中推断类型。

鉴于:

template<typename T> void foo(T);
template<typename T, T> void bar();

可以推导出Tfor foo(例如,foo(10)将导致T推导为 be int),但无法推导Tfor barbar<10>()将根本无法编译,您必须将其写为bar<int,10>())。

N3601建议通过引入语法来解决这个问题:

template<using typename T, T> void bar();

这将允许bar<10>()编译并导致类型T被推断。

于 2013-04-13T03:28:51.463 回答
5

论文介绍误导:成语其实是

 template <typename T, T t>

它表示一个依赖于类型T和该类型值t的模板。这个符号有点重,因为在大多数情况下,类型可以从值本身推导出来。

例如

// the current definition notation
template <typename T, T t> void f() { t.f(); };

//// the proposed definition notation
//// the parameter t depends on an implicit typename parameter T
// template <using typename T, T t> void f() { t.f(); };

struct foo {
    void f(){ 
        // some computation
    }
};

foo bar;

int main(){
    // the current instantiation notation
    f<foo,bar>(); 
    //// the proposed instantiation notation 
    //// we know that bar is of type foo, so we don't need to specify it
    // f<bar>();
}

该提议是关于引入一些“语法糖”以使符号更易于编写。

此外,上面给出的示例在其描述中是微不足道的(并且可能是错误的,因为模板参数需要是constexpr),但是本文描述了当前符号可能变得非常复杂的几种情况,从而降低了可读性和整体编程的易用性。

于 2013-04-13T03:29:58.633 回答