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

ein*_*ica 6 c++ templates code-duplication decltype explicit-instantiation

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

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

没有重载.我想明确地实例化它.我可以写(对于T= int):

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

但我真的不想复制那么长的宣言.我本来希望能说出类似的话:

template <typename T> using bar = decltype(foo<T>);
Run Code Online (Sandbox Code Playgroud)

然后:

template bar<int>;
Run Code Online (Sandbox Code Playgroud)

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

注意:我一直使用一个例子,你不能仅从参数中推断出类型,因为我想要任何解决方案来支持这种情况.

Bar*_*rry 3

当然。来自[temp.explicit]:

\n\n
\n

显式实例化的语法为:
\n     显式实例化:
\n extern opt template 声明

\n\n

[...] 如果显式实例化是针对函数或成员函数,则声明中的unqualified-id应该是template-id,或者(可以推导出所有模板参数)\n template-name或operator-函数 ID。[ 注意:该声明可以声明一个qualified-id,在这种情况下, qualified- id的\n unqualified-id必须是template-id。\xe2\x80\x94结束注]

\n
\n\n

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

\n\n
template <class T> void foo(T ) { }\n
Run Code Online (Sandbox Code Playgroud)\n\n

我们可以通过以下方式明确专业化:

\n\n
template void foo<char>(char );   // template-id\ntemplate void foo(int );          // or just template-name, if the types can be deduced\n
Run Code Online (Sandbox Code Playgroud)\n\n

这与编写的内容相同:

\n\n
using Fc = void(char );\nusing Fi = void(int );\n\ntemplate Fc foo<char>;\ntemplate Fi foo;\n
Run Code Online (Sandbox Code Playgroud)\n\n

这与编写的内容相同:

\n\n
template <class T> using F = decltype(foo<T> );\n\ntemplate F<char> foo<char>;\ntemplate F<int> foo;\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n