c++ - Lambda 函数无法调用函数模板参数的静态函数

标签 c++ c++11 lambda type-parameter

好的,所以我有一些基本上像这样的设置:

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>();
}

http://ideone.com/dRdpI

由于这似乎是 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/

相关文章:

c++ - 将双端队列 max_size 设置为最大大小

c++ - 使用 Boost::Fiber 的多个共享工作池

c++ - 顶级或低级常量或两者都不是?

java - 将带有方法引用的 lambda 转换为 Java 7 中的函数

c# - 如何构建这个 LINQ 表达式?

c++ - 如何判断一个类是否间接继承自基类?

c++ - 指针列表的成员函数

c++ - 我应该包括每个标题吗?

lambda - 如何将 lambda 表达式放在 mapTo 调用合法语法的参数之后?

c++ - 如何从元组中获取第 N 种类型?