英文:
Call a function using expansion pack on a same function
问题
以下是翻译好的部分:
我想能够调用一个函数,该函数接受任意数量的参数,每个参数的值由另一个函数提供:
template <typename T, std::size_t N>
class MyClass
{
public:
void doSomething()
{
doSomethingProxy(std::make_index_sequence<N>());
}
private:
template <std::size_t... I>
void doSomethingProxy(std::index_sequence<I...>)
{
m_obj.doSomething({get()...}); // T::doSomething() 期望一个具有 N 个参数的构造函数的对象,并且我想为该构造函数的每个参数调用 get() 函数 N 次
}
int get() { return 0; }
T m_obj{};
};
然而,执行上述操作会导致错误:
错误:扩展模式 get() 不包含参数包
我认为问题在于 get()...
不依赖于 I
,但我不确定如何解决这个问题。
英文:
I would like to be able to call a function over any number of arguments, with each argument's value supplied by another function:
template <typename T, std::size_t N>
class MyClass
{
public:
void doSomething()
{
doSomethingProxy(std::make_index_sequence<N>());
}
private:
template <std::size_t... I>
void doSomethingProxy(std::index_sequence<I...>)
{
m_obj.doSomething({get()...}); // T::doSomething() expects an object whose constructor has N number of arguments, and I would like to call the get() function for each argument of said constructor, N times
}
int get() { return 0; }
T m_obj{};
};
However doing the above results in the error
error: expansion pattern get() contains no parameter packs
I think the issue is that get()...
does not depend on I
, but I'm not sure how to solve this problem.
答案1
得分: 3
(I,get())
使用参数包,并导致 get()
(逗号操作符,评估两个操作数,返回右操作数)。为了消除关于逗号操作符左操作数无效的警告,您可能需要写成 ((void)I,get())
:
#include <cstdint>
#include <utility>
template <typename T, std::size_t N>
class MyClass
{
public:
void doSomething()
{
doSomethingProxy(std::make_index_sequence<N>());
}
private:
template <std::size_t... I>
void doSomethingProxy(std::index_sequence<I...>)
{
m_obj.doSomething({ ((void)I,get())... });
}
int get() { return 0; }
T m_obj{};
};
英文:
(I,get())
is using the parameter pack and results in get()
(comma operator, evaluates both operands, returns the rhs). To silence a warning about no effect of lhs of comma operator you might need to write ((void)I,get())
:
#include <cstdint>
#include <utility>
template <typename T, std::size_t N>
class MyClass
{
public:
void doSomething()
{
doSomethingProxy(std::make_index_sequence<N>());
}
private:
template <std::size_t... I>
void doSomethingProxy(std::index_sequence<I...>)
{
m_obj.doSomething({ ((void)I,get())... });
}
int get() { return 0; }
T m_obj{};
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论