将成员函数传递给模板函数时,会出现语法错误
Getting syntax error upon passing the member function to template function
首先,我使用C 17标准。
除非我尝试在具有相同模板函数的类中使用它,否则我对工作的代码很好。
以下代码行:
auto t = make_tuple_seq(std::make_index_sequence<numArgs>{}, &lzuint<T, A...>::helper);
沿着"无法初始化"的线的10个汇编错误,我坦率地看不见。
我以前的尝试是使用lambda功能而不是辅助成员函数,这也导致了不可读的错误。
在这里我提供最小代码:
#include <iostream>
#include <vector>
#include <functional>
#include <string>
#include <tuple>
template<typename _func, size_t... I>
auto make_tuple_seq(std::index_sequence<I...>, _func&& func)
{
return std::make_tuple(func(I)...);
}
constexpr const auto numArgs = 2;
template<typename T, typename... A>
class lzuint
{
protected:
size_t helper(size_t i)
{
return this->body.size() - numArgs + i;
}
public:
lzuint(const std::function<T(A...)>& func, A... args) : f(func), body({ args... }) {}
const uint32_t& operator[](size_t index)
{
auto t = make_tuple_seq(std::make_index_sequence<numArgs>{}, &lzuint<T, A...>::helper);
while (body.size() - 1 < index)
body.push_back(std::apply(f, std::move(t)));
return body[index];
}
private:
std::vector<T> body;
std::function<T(A...)> f;
};
using ullong = unsigned long long;
int main()
{
auto tup = make_tuple_seq(std::make_index_sequence<N>{}, [&v](size_t i) {return v[i]; });//Note:this one works just fine
lzuint<uint32_t, uint32_t, uint32_t> lzu([](uint32_t i, uint32_t j) { return i + j; }, 1, 1);
lzu[1];
lzu[10];
lzu[11];
lzu[12];
lzu[13];
return 0;
}
我目前正在尝试通过创建SMTH之类的SMTH,例如"懒惰评估"技术的SMTH,这将不胜感激。
。我得到的第一个错误是
source.cpp(19): error C2064: term does not evaluate to a function taking 1 arguments
lzuint<T, A...>::helper
是一个非静态成员函数。它需要调用一个对象。对象(将其变为函数内部的this
指针)通常作为隐藏的第一个参数传递,因此函数不采用一个参数的消息。
有两种解决方法:要么使用lambdas
auto t = make_tuple_seq(std::make_index_sequence<numArgs>{},
[this](size_t i) { return helper(i); });
或使用std::bind
:
auto t = make_tuple_seq(std::make_index_sequence<numArgs>{},
std::bind(&lzuint<T, A...>::helper, this, std::placeholders::_1));
使用lambdas通常是推荐的解决方案。
相关文章:
- C++使用 rand 定义函数语法
- QObject::连接不起作用 - 使用函数语法找不到信号
- C++ std::函数语法问题
- 如何在不更改现有函数语法的情况下将普通指针替换为共享指针
- 模板化函数语法错误中使用的模板化类中的嵌套类
- C 变化函数语法
- 返回语句中的构造函数语法
- 复制构造函数语法错误:myclass 没有成员 mymember
- C++.传递给函数.语法问题
- C++可视化工作室函数语法突出显示
- 在 c++ 中移动 2d 数组的构造函数(语法逻辑不清楚):
- c 通过值或指针函数语法
- 正确的朋友模板函数语法
- C++类构造函数语法的解释
- C++ 使用指针移动构造函数(*&&&语法)
- 复制构造函数语法并显示构造函数的值
- 回调函数语法
- 类模板专用化中的成员函数语法
- C++学习函数语法
- 使用模板 C++ 的友元函数语法错误