考虑以下,最小的例子,当不编译(编译没有#1
和#2
):C++模板通过函数签名
void foo(void)
{ }
template<typename T> class Stage2;
template<typename Ret, typename... Args>
struct Stage2<Ret (Args...)>
{
template<Ret (*func)(Args...)>
static void foobar(void)
{ /* Do something */ }
};
template<typename FuncType>
struct Stage1
{
template<FuncType func>
static void bar(void)
{
Stage2<FuncType>::foobar<func>(); // #1, Not working
Stage2<decltype(func)>::foobar<func>(); // #2, Not working
Stage2<void()>::foobar<func>(); // #3, Working
}
};
int main(void)
{
Stage1<decltype(foo)>::bar<foo>();
return 0;
}
为何不与#1
和#2
编译,而它编译只是#3
罚款?在我看来,只要foo的签名为void()
,#3
应该与其他人相同,在本例中它就是这样做的。即使编译器告诉我,FuncType
实际上是void()
(见下文)。
错误信息(同为#1
和#2
):
main.cpp: In static member function ‘static void Stage1<FuncType>::bar()’:
main.cpp:21:40: error: expected primary-expression before ‘)’ token
Stage2<FuncType>::foobar<func>(); // #1, Not working
^
main.cpp: In instantiation of ‘static void Stage1<FuncType>::bar() [with FuncType func = foo; FuncType = void()]’:
main.cpp:29:37: required from here
main.cpp:21:33: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘void (*)()’ to binary ‘operator<’
Stage2<FuncType>::foobar<func>(); // #1, Not working
~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
缺少什么我在这里?我正在使用g ++ 7.2.0。
注意:如果这样做有用,我不会真正感兴趣,我只想知道它为什么不编译,因为它对我没有意义。
从来没有听说过这种语法,很高兴知道。谢谢! – Shadowigor