非类型可变参数模板参数

时间:2018-09-12 13:25:30

标签: c++ c++17 variadic-templates

我想使用可变参数wchar *值参数创建类。请考虑以下示例。

template<const wchar_t* ...properties>
class my_iterator{
public:
     std::tuple<std::wstring...> get(); // quantity of wstrings depend on quantity of template parameters
};

我想像下面这样使用

my_iterator<L"hello", L"world"> inst(object_collection);
while(inst.next()){
    auto x = inst.get();
}

但是当我实例化该类时,我会收到编译错误。

  

错误C2762:“ my_iterator”:无效的表达式作为以下内容的模板参数   “属性”

怎么了?怎么办?

3 个答案:

答案 0 :(得分:3)

这与 variadic non-type 的模板参数无关-字符串文字不能简单地用作模板参数(直到P0732-被接受-成为现实。

template <const char*> struct foo { };
foo<"hi"> x;

也会失败。 live example on godbolt.org

  

错误:“'hi”'不是'const char *'类型的有效模板参数,因为在这种情况下永远不能使用字符串文字

答案 1 :(得分:3)

出问题的是[temp.arg.nontype] §2.3。字符串文字不能(当前)用作模板参数。例如,您可以做的是声明命名的数组对象并将其用作参数:

template<const wchar_t* ...properties>
class my_iterator {};


int main()
{
    static constexpr const wchar_t a[] = L"hello";
    static constexpr const wchar_t b[] = L"world";

    my_iterator<a, b> inst;
}

工作示例here

答案 2 :(得分:1)

另一种方法是逐个传递字符,

#include <tuple>

template<wchar_t ...properties>
class my_iterator{
public:
     std::tuple<decltype(properties)...> get(); // quantity of wstrings depend on quantity of template parameters
};

my_iterator<L'h', L'e',  L'l', L'l', L'o'> inst;
相关问题