简单的可变参数模板函数不能实例化 [英] Simple variadic template function can't instantinate
问题描述
我知道 sizeof ...(Args ...)
产生了C ++ 0x打包模板参数列表中的类型数,但我想要
I'm aware that sizeof...(Args...)
yields the number of types in a C++0x packed template argument list, but I wanted to implement it in terms of other features for demonstation purposes, but it won't compile.
// This is not a solution -- overload ambiguity.
// template <typename... Args> size_t num_args (); // Line 7
// template <>
constexpr size_t num_args ()
{
return 0;
}
template <typename H, typename... T>
constexpr size_t num_args () // Line 16
{
return 1 + num_args <T...> (); // *HERE*
}
int main ()
{
std :: cout << num_args <int, int, int> ();
}
此错误在 * HERE *
与
No matching function call to ...
... candidate is template<class H, class ... T> size_t num_args()
它没有看到首先定义的基本案例。转发声明模板< typename ... T> num_args();
在重载解析中引入歧义。
i.e. it's not seeing the base case which is defined first. Forward-declaring template<typename...T>num_args();
introduces ambiguity in overload resolution.
x.cpp:30:45: note: candidates are:
x.cpp:7:36: note: size_t num_args() [with Args = {int, float, char}, size_t = long unsigned int]
x.cpp:16:9: note: size_t num_args() [with H = int, T = {float, char}, size_t = long unsigned int]
我使用gcc 4.6。如何使这项工作?
I am using gcc 4.6. How can I make this work?
感谢。
推荐答案
没有声明基本案例。您有 num_args
函数的无模板重载,但调用函数 num_args
You didn’t declare a base case. You have a template-free overload of your num_args
function but when calling a function num_args<T...>()
this will never be found, for obvious reasons: it will always try to instantiate a function template.
template <>
constexpr size_t num_args<>()
{
return 0;
}
但是,这不会工作,因为这里你专门化一个无参数函数模板和这样的模板不存在:您的其他函数模板 num_args
始终至少有一个参数 H
。
However, this won’t work either since here you’re specialising a parameterless function template and such a template doesn’t exist: your other function template num_args
always has at least one argument, H
.
为了真正使这项工作,你需要部分专业化,这些只存在于类模板。这是您在这里需要的。
In order to really make this work you need partial specialisations, and these only exist for class templates. So this is what you need here.
template <typename T>
struct num_args_t;
template <>
struct num_args_t {
static size_t const value = 0;
};
template <typename H, typename T...>
struct num_args_t {
static size_t const value = num_args_t<T...>::value + 1;
};
template <typename T...>
constexpr size_t num_args() {
return num_args_t<T...>::value;
}
这篇关于简单的可变参数模板函数不能实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!