Variadic模板功能:专门的头/尾和空基座

lee*_*mes 13 c++ templates template-meta-programming variadic-templates c++11

我想在类中有一个可变参数模板函数.可变参数模板参数是字符,应该以类似循环的方式处理.所以我想把它写成haskell,头部/尾部分割列表,直到达到基本情况(空列表).

举个例子,让我们只计算给出的参数数量(只是一个最小的例子).

我想出了以下代码:

struct MyClass {
    template<char ...X>
    static int count();
};


template<>
int MyClass::count<>() {
    return 0;
}
template<char Head, char ...Tail>
int MyClass::count<Head, Tail...>() {
    return 1 + count<Tail...>();
}
Run Code Online (Sandbox Code Playgroud)

但是,这似乎不起作用:

prog.cpp:12:35: error: function template partial specialization ‘count<Head, Tail ...>’ is not allowed
prog.cpp:12:5: error: prototype for ‘int MyClass::count()’ does not match any in class ‘MyClass’
prog.cpp:3:16: error: candidate is: template<char ...X> static int MyClass::count()
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我知道功能不支持部分特化.但我认为将变量模板专门设计为头/尾和空基本案例版本不是局部专业化而是完全专业化,但也许我错了?我是否需要将其写为类而不是函数?

我发现了一些示例(printf),它们在不使用模板语法的情况下实现了基本情况.但我想我的情况有所不同,因为对printf的调用不使用模板语法而是类型推导,所以printf(tail...)调用printf()if tail为空.另一方面,在我的情况下,当调用基本情况时,count<>()不一样count().

And*_*owl 18

我想说重载函数模板通常是一个更好的主意,而不是专门化它们:

struct MyClass {
    template<typename... Tail>
    static int count() {
        return 0;
    }

    template<char Head, char... Tail>
    static int count() {
        return 1 + count<Tail...>();
    }
};

#include <iostream>

int main() {
    std::cout << MyClass::count<'f','o','o'>();
}
Run Code Online (Sandbox Code Playgroud)

这是一个实例.我还要提到内置运算符sizeof...可用于此目的:

struct MyClass {
    template<char... Chars>
    static int count() {
        return sizeof...(Chars);
    //         ^^^^^^^^^
    }
};
Run Code Online (Sandbox Code Playgroud)