【发布时间】:2019-10-20 09:46:03
【问题描述】:
我有多个课程(为简单起见,此处为Foo 和Bar)
struct Bar {};
struct Foo {};
以及一个接受单个模板参数并根据该类型执行某些操作的函数:
template <typename T>
constexpr void doSomething() { cout << "Am I a Foo? " << is_same<T,Foo>::value << endl; }
在我的代码中,我得到了Foos 和Bars 的模板参数包,我应该对它们中的每一个都调用doSomething() 函数(我不关心其中的顺序)执行哪些函数)。
doStuff<Foo, Bar, Bar>(); // --> True / False / False
到目前为止,我能想到的唯一解决方案是:
template <typename... Ts>
class Doer;
template <>
struct Doer <> {
static constexpr void doStuff() {}
};
template <typename Head, typename... Tail>
struct Doer <Head, Tail...> {
static constexpr void doStuff() {
doSomething<Head>();
Doer<Tail...>::doStuff();
}
};
template <typename... Ts>
constexpr void doStuff() {
return Doer<Ts...>::doStuff();
}
doStuff<Foo, Bar, Bar>(); // --> True / False / False
它有效,但我觉得它相当混乱。我不得不使用带有部分特化的类模板,因为函数模板只支持完全特化。我也试过了
constexpr void doStuff() { }
template <typename Head, typename... Tail>
constexpr void doStuff() {
doSomething<Head>();
doStuff<Tail...>(); // --> Compile Error
}
但编译器失败了,因为它无法确定doStuff<>() 实际上是doStuff()。如果我的可变参数函数中有参数,那么编译器足够聪明地解决这个冲突,因为它应用了模板类型推导:
constexpr void doStuff() { }
template <typename Head, typename... Tail>
constexpr void doStuff(Head arg, Tail... args) {
doSomething<Head>();
doStuff(args...);
}
Foo f1;
Bar b1, b2;
doStuff<Foo, Bar, Bar>(f1, b1, b2); // --> True / False / False
我错过了什么吗?有没有办法让我的可变参数函数在不使用函数参数或类模板的情况下工作?
【问题讨论】:
标签: c++ variadic-templates variadic-functions template-meta-programming function-templates