1
我已阅读下列问题:静态模板函数可以通过编译器内联吗?
- Template functors vs functions
- C++ Functors - and their uses
- C++ function template partial specialization?
我明白C++ functors
是良好的。但我不能推断,如果将执行以下操作会发生什么:
template <typename T, unsigned int state>
class Foo {
public:
static Foo_func() { /* Do something */ };
}
// Partial specialization:
// -- state == 1
template <typename T>
class Foo <T, 1> {
public:
static Foo_func() { /* Do something */ };
}
template <typename F>
void call_func(F func) {
// Do something... //
func();
// Do something... //
}
int main() {
Foo <double, /*state*/ 1> obj;
// Case 1:
call_func(obj.Foo_func);
// Case 2:
call_func(Foo<double, /*state*/ 1>::Foo_func);
}
考虑脚本编译器将能够为嵌入式Foo_func()
?
看看程序集,看看编译器做了什么。一个很好的资源是https://gcc.godbolt.org/ – NathanOliver
你的代码不能编译的原因很多。对于它的价值,编译器应该能够将调用内联到'func',但是我怀疑它只会在call_func本身被内联时才这样做。 [在这个简单的代码中,编译器内嵌了所有内容](https://godbolt.org/g/8KmlTv)。 – Cornstalks
一般来说,您无法可靠地推断优化,请始终检查asm。在这种情况下,FWIW Clang和GCC都将这些内联列出,但他们可能并不总是这样做。 – harold