use*_*342 6 c++ lambda type-parameter c++11
好的,所以我有一些基本上像这样的设置:
template<typename T> void example()
{
std::function<int (byte*)> test = [=](byte* start) -> int
{
return T::magic(start);
}
}
Run Code Online (Sandbox Code Playgroud)
忽略这些裸体调用的"不洁"程度,它也不会编译,给出这些错误:
'T' : is not a class or namespace name
'magic': identifier not found
Run Code Online (Sandbox Code Playgroud)
有没有办法能够在泛型类型名称T上进行调用,假设我将始终使用具有函数magic(byte*start)的类调用example()?当然,我不必为将要执行此操作的每个类重新声明此模板函数.
我在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>();
}
Run Code Online (Sandbox Code Playgroud)
由于这似乎是 VC10 的 lambda 实现中的一个错误,因此可能的解决方法是创建一个本地函子类:
template<typename T> void example()
{
struct Foo {
int operator()(byte * start) { return T::magic(start); }
};
std::function<int (byte*)> test = Foo();
}
Run Code Online (Sandbox Code Playgroud)