gpt4 book ai didi

c++ - 奇怪的错误 C2275 ... 非法使用此类型作为具有成员函数模板和 lambda 的表达式

转载 作者:太空狗 更新时间:2023-10-29 20:06:44 24 4
gpt4 key购买 nike

总结

出于某种原因,我的调用 lambda 函数的成员函数模板无法编译并出现 error C2275 ... 非法使用此类型作为表达式,但是当函数被移出时它可以正确编译的免费函数。

详情

首先,我有一个基类,它将 function 实例保存在 vector 中。只有派生类可以通过调用 add_external 向该 vector 添加 function 实例。所有 function 实例都可以通过调用 invoke_externals 来公开调用。派生类将添加 lambda 作为 function 实例。这些 lambda 将依​​次使用另一个“内部”lambda 调用基类函数模板 invoke_internalinvoke_internal 的模板参数是一种异常类型,在 invoke_internal 中执行“内部”lambda 时将被显式捕获:

using namespace std;

class base
{
public:
void invoke_externals()
{
for (auto it = funcs_.begin(); it != funcs_.end(); ++it)
{
(*it)();
}
}

protected:
void add_external(function<void(void)> func)
{
funcs_.push_back(func);
}

template <typename T>
void invoke_internal(function<void(void)> func)
{
try
{
func();
}
catch (const T&){}
catch (...){}
}

vector<function<void(void)>> funcs_;
};

然后我有两个简单的免费函数,它们会抛出 logic_errorruntime_error 异常。这些函数将在 invoke_internal 中调用的“内部”lambda 中使用:

void throws_logic_error()
{
throw logic_error("");
}

void throws_runtime_error()
{
throw runtime_error("");
}

derived 类的构造函数中,使用add_external 添加了两个lambda。这些 lambda 中的每一个都使用“内部”lmbda 调用 invoke_internal。第一次调用 invoke_internal 将明确捕获 throws_logic_error 将抛出的 logic_error。第二次调用 invoke_internal 将明确捕获 throws_runtime_error 将抛出的 runtime_error

class derived : public base
{
public:
derived()
{
add_external([this]()
{
invoke_internal<logic_error>([]()
{
throws_logic_error();
});
});

add_external([this]()
{
invoke_internal<runtime_error>([]()
{
throws_runtime_error();
});
});
}
};

为了将所有这些结合在一起,derived 被实例化并调用 invoke_externals 以调用添加到 derived 构造函数中的“外部”lambda .那些“外部”lambda 将依​​次调用“内部”lambda,抛出的异常将被显式捕获:

int wmain(int, wchar_t*[])
{
derived().invoke_externals();

return 0;
}

问题

但是,上面的不编译:

error C2275: 'std::logic_error' : illegal use of this type as an expression
error C2275: 'std::runtime_error' : illegal use of this type as an expression

...在 derived 构造函数中调用 invoke_internal 时发出。

如果我将 invoke_internalbase 移出并使其成为一个自由函数,那么它就会编译。

问题

当函数模板是 base 成员时,为什么我会得到error C2275 ...非法使用此类型作为表达式

注意:将有问题的函数移出 base 并不是最佳选择,因为在我的现实生活场景中,该函数实际上确实以不同的方式使用其类的状态。

最佳答案

感谢@sehe 的回答,我可以在 VS2010 上自己测试这个。以下代码有效:

derived()
{ // vvvvvvvvvvvvvv
add_external([this] () { this->template invoke_internal<logic_error>([]() { throws_logic_error(); }); });

add_external([this] () { this->template invoke_internal<runtime_error>([]() { throws_runtime_error(); }); });
} // ^^^^^^^^^^^^^^

不要问我为什么。通常,您收到的错误意味着未检测到使用该类型的模板。

通常这应该只发生在依赖类型/嵌套模板中,并且可以在相关模板之前直接使用 template 解决(如图所示),它告诉编译器遵循模板(duh)。不过,我们在此之前需要 this->,否则它看起来像是一个显式实例化,这本身就是错误的:

template Foo<int>; // explicitly instantiate the Foo class template for int

现在。奇怪的是,这里也出现了这个问题,我只能同意@sehe 的观点,这看起来像是一个编译器限制。

关于c++ - 奇怪的错误 C2275 ... 非法使用此类型作为具有成员函数模板和 lambda 的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6432658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com