将成员函数传递给模板函数时,会出现语法错误

Getting syntax error upon passing the member function to template function

本文关键字:函数 语法 错误 成员      更新时间:2023-10-16

首先,我使用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通常是推荐的解决方案。