我最近遇到这样的代码
template <typename T>
void Foo()
{
T::Bar();
}
我很困惑,那是如何编译的?没有像 C# 泛型中那样对 T 的限制。
我意识到模板不像泛型,因为前者基本上是美化的宏,所以 Foo
的每次使用都是针对中提供的 T
编译的那个实例,假设它有一个 Bar()
函数,它能工作吗?有点像鸭子打字?
这是自 c++03 以来的工作方式还是 c++11 中的新内容?
最佳答案
这个模板函数只是强加了在代入类型T时,表达式T::Bar();
是有效的,只要有效就可以编译(没有C#-就像 C++ 中的约束):
以下是使用您的模板的两个示例:
#include <iostream>
#include <functional>
struct X
{
static void Bar() { std::cout << "Bar X\n!"; }
};
struct Y
{
static std::function<void(void)> Bar;
};
std::function<void(void)> Y::Bar = []() { std::cout << "Bar Y!"; };
template <typename T>
void Foo()
{
T::Bar();
}
int main()
{
Foo<X>();
Foo<Y>();
return 0;
}
关于c++ - 调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25400592/