好的,所以我有一些基本上像这样的设置:
template<typename T> void example()
{
std::function<int (byte*)> test = [=](byte* start) -> int
{
return T::magic(start);
}
}
忽略进行这些裸调用是多么“不干净”,它也无法编译,并给出以下错误:
'T' : is not a class or namespace name
'magic': identifier not found
假设我将始终使用具有函数 magic(byte* start) 的类调用 example(),是否有任何方法能够调用通用类型名称 T?当然,我不必为将执行此操作的每个类重新声明此模板函数。
我在 VC++ 2010 中这样做,看起来它可能是一个编译器错误。任何可能的解决方法?
最佳答案
唯一的错误是缺少分号。一旦修复,它就可以正常工作。
#include <iostream>
#include <functional>
typedef unsigned char byte;
template<typename T> void example()
{
std::function<int (byte*)> test = [=](byte* start) -> int
{
return T::magic(start);
}; // <--------------------------------- You were missing that
}
struct Foo {
static int magic(byte*);
};
int Foo::magic(byte* start)
{
std::cout << "magic\n";
}
int main()
{
example<Foo>();
}
由于这似乎是 VC10 的 lambda 实现中的一个错误,一个可能的解决方法是创建一个本地仿函数类:
template<typename T> void example()
{
struct Foo {
int operator()(byte * start) { return T::magic(start); }
};
std::function<int (byte*)> test = Foo();
}
关于c++ - Lambda 函数无法调用函数模板参数的静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8113115/