(额外:直接回答你的第一个问题,你也可以template<class...T, T... t> void func() {}
变成模板内的模板。这在g ++ 4.6中不起作用,但在clang 3.0中起作用,因此我花了一段时间才找到它。 )
将模板放入模板中:
template<class ... T>
struct func_types {
template <T ... t>
static void func_values() {
// This next line is just a demonstration, and
// would need to be changed for other types:
printf("%c %d\n", t...);
}
};
int main() {
func_types<char, int> :: func_values<'A', 10>();
}
模板内的模板是否可以接受?另一种方法是将元组与func< tuple<char,int> , make_tuple('A',10) >
. 我认为这是可行的,但您可能必须推出自己的元组类(看起来 make_tuple 不是constexpr
.
最后,您也许可以按如下方式实现您的 Foo 模板:
template<typename Ret, typename ...Args>
struct Foo {
template< Ret (*func)(Args...)>
struct Bar {
template<typename T...>
Bar(T&&... args) {
cout << "executing the function gives: "
<< func(std::forward(args)...) << endl;
}
};
};
int main () {
Foo<size_t, const char*> :: Bar<strlen> test1("hi");
Foo<int, const char*, const char*> :: Bar<strcmp> test2("compare","these");
}
后一个代码在ideone上。为了演示,我实现了一个构造函数来将 args 转发到模板中的代码函数。