template<typename T> void foo(T);
template<typename T, T> void bar();
在foo
中,可以推断出T
(例如,foo(10)
的结果将导致T
被推断为int
),但是在bar
中无法推断出T
(bar<10>()
将无法编译,您必须将其编写为bar<int,10>()
)。
N3601提议通过引入以下语法来修复此问题:
template<using typename T, T> void bar();
这将允许bar<10>()
编译,并导致类型T
被推断出来。
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
),但该论文描述了几种情况,当前符号表示法可能变得非常复杂,降低可读性和整体编程便利性。t
必须是整数常量或指针,因为模板参数中不允许出现其他内容。 - v.oddou
template <typename T> void foo(T t);
。将该参数变为编译时值:template <typename T, T t> void bar();
(我认为您是指这个而不是class
)。现在考虑如何调用foo(5);
使 T 成为int
,但要使用bar
,您需要bar<int, 5>();
。这样做是否朝着正确的方向发展? - chris