我有一个函数将std::function
作为参数。但是,我想确保传入的函数不允许修改传递给它的参数。将lambdas转换为std :: function时强制执行正确性正确性
这里是函数的简单版本(注意:T
就可以了,通常,参考):
template <class T>
void Bar(std::function<void(std::add_const_t<T>)> func)
{
// ...
}
不好的用法:
Bar<int&>([](int&) { /* Do nasty stuff! */ }); /* A-OK! */
我希望禁止这种使用,但是这段代码编译得非常好,即使我觉得它不应该。
有趣的事情是,如果我摆脱模板参数,即:
void Bar(std::function<void(const int&)> func)
{
// ...
}
然后,这种用法不会进行编译(因为它不应该):
Bar([](int&) { /* Do nasty stuff! */ }); /* Error C2664 */
如何我可以执行此操作并仍保留模板参数吗?
注'的std :: add_const_t''是INT&'。 –
aschepler
@aschepler我在文档中也看到了这一点。所以我甚至试着做一个hacky版本:'const T',我想这会推演到'const int&'。但不是。即使我用'const T'替换'std :: add_const_t',它仍然编译得很好。 –
Zeenobit
@Zeenobit:模板不是宏的。这更类似于'typedef int & T; T const ref;' - 再次'ref'将是'int&'。还要比较指针:'typedef int * T; T const ptr'让你获得一个'int * const'而不是'int const *'。 – MSalters