我有一个很长的模板函数声明:
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()
一些其他方式来避免复制实例化的声明吗?
注意:我特意使用了一个示例,在该示例中您不能仅从参数推断出类型,因为我希望任何解决方案也支持这种情况。
最佳答案
当然。来自 [temp.explicit]:
The syntax for explicit instantiation is:
explicit-instantiation:
externopttemplate
declaration[...] If the explicit instantiation is for a function or member function, the unqualified-id in the declaration shall be either a template-id or, where all template arguments can be deduced, a template-name or operator-function-id. [ Note: The declaration may declare a qualified-id, in which case the unqualified-id of the qualified-id must be a template-id. —end note ]
我们需要一份声明。假设我们从:
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>
的原因不起作用是因为它不是声明。你也需要这个名字。
关于c++ - 我可以使用 decltype() 来避免显式模板实例化中的代码重复吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558915/