在C++ 11模板中,有没有办法将元组用作(可能是模板)函数的各个args?
示例:
假设我有此功能:
void foo(int a, int b)
{
}
Run Code Online (Sandbox Code Playgroud)
我有元组auto bar = std::make_tuple(1, 2).
我可以用它以foo(1, 2)一种模板的方式打电话吗?
我的意思并不简单,foo(std::get<0>(bar), std::get<1>(bar))因为我想在一个不知道args数量的模板中这样做.
更完整的例子:
template<typename Func, typename... Args>
void caller(Func func, Args... args)
{
auto argtuple = std::make_tuple(args...);
do_stuff_with_tuple(argtuple);
func(insert_magic_here(argtuple)); // <-- this is the hard part
}
Run Code Online (Sandbox Code Playgroud)
我应该注意,我宁愿不创建一个适用于一个arg的模板,另一个适用于两个arg的模板等等...
对于这个非变量的例子:
int Func1();
double Func2();
void MyFunc( int, double );
int main()
{
MyFunc( Func1(), Func2() );
//...
}
Run Code Online (Sandbox Code Playgroud)
它没有规定是否Func1()还是Func2()先计算,只是两者都必须做之前MyFunc()被调用.
这个测序如何与可变参数的扩展一起工作?
template < typename Func, typename ...Args >
void MyFunc2( Func &&f, Args&& ...a )
{
int b[] = { f( std::forward<Args>(a) )... };
//...
}
Run Code Online (Sandbox Code Playgroud)
假设这f是一个在第一次调用后改变其状态的函数对象.是否会f为每个段调用a?换句话说,将f在a列表中的第一个项目,然后第二个项目,第三个项目等上调用,而不是随机跳过扩展列表?我们曾经在每个项目之间调用序列点吗?
c++ variadic-functions sequence-points variadic-templates c++11
假设:
template<class T,int N>
struct A {
A(): /* here */ {}
T F[N];
};
Run Code Online (Sandbox Code Playgroud)
我需要F[]构造的元素{0,1,2,...,N-1}.如果可能的话,我想避免递归定义的模板结构,定义最后一个级别,template<class T> struct A<T,0>并做一些复杂的模板技巧.C++ 11初始化列表可以帮助吗?
有谁知道,如果有关于c ++语言功能的标准建议,可以让我取代它(感谢Yakk):
template<class... ARGS>
void bar(const ARGS& ... args) {
auto t = { (foo(args),0)... };
(void) t; //<- prevent warning about unused variable
}
Run Code Online (Sandbox Code Playgroud)
像这样更自然:
template<class... ARGS>
void bar(const ARGS& ... args) {
foo(args)...;
}
Run Code Online (Sandbox Code Playgroud)
foo 例如函数,函数模板和/或它们的重载集合,它们的返回类型可能是无效的(或者通常我不关心)。
顺便说一句,如果有人知道用c ++ 14编写的更简洁的方法,可以随意分享,但是我认为,这个问题已经解决了
我有多个类(Foo和Bar这里简单)
struct Bar {};
struct Foo {};
Run Code Online (Sandbox Code Playgroud)
和一个采用单个模板参数并根据该类型执行某些操作的函数:
template <typename T>
constexpr void doSomething() { cout << "Am I a Foo? " << is_same<T,Foo>::value << endl; }
Run Code Online (Sandbox Code Playgroud)
在我的代码中,为我提供了Foos和Bars 的模板参数包,并且应该doSomething()在它们的每个参数上调用函数(我不在乎函数的执行顺序)。
doStuff<Foo, Bar, Bar>(); // --> True / False / False
Run Code Online (Sandbox Code Playgroud)
到目前为止,我唯一能想到的解决方案是:
template <typename... Ts>
class Doer;
template <>
struct Doer <> {
static constexpr void doStuff() {}
};
template <typename Head, typename... Tail>
struct Doer <Head, Tail...> {
static constexpr void …Run Code Online (Sandbox Code Playgroud) c++ variadic-functions function-templates template-meta-programming variadic-templates