6

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

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()其他方式来避免复制实例化的声明吗?

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

4

1 回答 1

3

当然。来自 [temp.explicit]:

显式实例化的语法是:
    explicit-instantiation :
        extern opt template declaration

[...] 如果显式实例化是针对函数或成员函数,则声明中的unqualified-id应为模板 ID,或者在可以推导出所有模板参数的情况下, 模板名称操作符函数-身份证[注意:声明可以声明一个qualified-id,在这种情况下qualified-id的 unqualified - id必须是一个template-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>不起作用的原因是它不是声明。你也需要名字。

于 2016-04-11T21:07:16.117 回答