非类型可变参数模板参数[重复]

问题描述 投票:2回答:3

这个问题在这里已有答案:

我想用variadic wchar * value参数创建类。请考虑以下示例。

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':无效表达式作为'属性'的模板参数

怎么了,该怎么办?

c++ c++17 variadic-templates
3个回答
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


3
投票

这与模板参数是无差异或非类型无关 - 字符串文字不能简单地用作模板参数(直到P0732 - 被接受 - 变为现实)。

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

也会失败。 live example on godbolt.org

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


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;
© www.soinside.com 2019 - 2024. All rights reserved.