我可以使用decltype()来避免显式模板实例化中的代码重复吗



我有一个长模板函数声明:

template <typename T> void foo(lots ofargs, goin here, andeven more, ofthese arguments, they just, dont stop);

没有过载。我想显式地实例化它。我可以写(比如T=int):

template void foo<int>(lots ofargs, goin here, andeven more, ofthese arguments, they just, dont stop);

但我真的不想复制那个冗长的声明。我会喜欢能够说出这样的话:

template <typename T> using bar = decltype(foo<T>);

然后:

template bar<int>;

现在,第一行编译(GCC 4.9.3),但第二行没有。我能以某种方式让它工作吗?或者我可以使用decltype()以其他方式避免复制实例化的声明吗?

注意:我特意使用了一个例子,在这个例子中,您不能仅从参数推断类型,因为我希望任何解决方案也支持这种情况。

当然。来自[显式温度]:

显式实例化的语法为:
 nbsp nbsp显式实例化
 nbsp nbsp nbsp nbsp;externopttemplate声明

[…]如果显式实例化是针对函数或成员函数的,则声明中的非限定id应为模板id板名称运算符函数id[注意:声明可以声明一个限定id,在这种情况下合格id的不合格id必须是模板id-尾注]

我们需要一份声明。让我们假设我们从开始

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

我们可以通过以下方式明确地进行专门化:

template void foo<char>(char );   // template-id
template void foo(int );          // or just template-name, if the types can be deduced

这和写的一样:

using Fc = void(char );
using Fi = void(int );
template Fc foo<char>;
template Fi foo;

这和写的一样:

template <class T> using F = decltype(foo<T> );
template F<char> foo<char>;
template F<int> foo;

基本上,template bar<int>不起作用的原因是它不是一个声明。你也需要这个名字。

最新更新