Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 非类型可变模板参数_C++_C++17_Variadic Templates - Fatal编程技术网

C++ 非类型可变模板参数

C++ 非类型可变模板参数,c++,c++17,variadic-templates,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_迭代器{ 公众: std::tuple get();/

我想用可变的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_迭代器{
公众:
std::tuple get();//wstring的数量取决于模板参数的数量
};
我想像下面那样使用它

my_iterator<L"hello", L"world"> inst(object_collection);
while(inst.next()){
    auto x = inst.get();
}
my_迭代器inst(对象集合);
while(inst.next()){
自动x=安装获取();
}
但是当我实例化这个类时,我收到了编译错误

错误C2762:“my_迭代器”:作为的模板参数的表达式无效 “财产”


有什么问题,该怎么办?

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

模板结构foo{};
富x;
也会失败

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

问题是。字符串文本(当前)不能用作模板参数。例如,您可以声明命名数组对象并将其用作参数:

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;
}
模板
类my_迭代器{};
int main()
{
静态constexpr const wchar_t a[]=L“hello”;
静态constexpr const wchar_t b[]=L“世界”;

我的迭代器另一种选择是逐个传递字符

#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;
#包括
模板
类my_迭代器{
公众:
std::tuple get();//wstring的数量取决于模板参数的数量
};
我的迭代器仪器;

什么是“测试”?这真的是您在这里显示的代码中的错误吗?还有
而(inst)
,这应该如何编译?可能与实际问题无关,但仍然会分散注意力。我读到了,指向对象的指针可以是模板参数。为什么不可以?@AlexeySubbota
“嗨”
不是
const char*
类型。它是
const char[3]
,它与P0732字符串文本不一样,不能与
const char*
模板参数一起使用,您必须使用自己的类型。如果不在库中实际包含P0732的示例实现,似乎有点痛苦。上周出于同样的原因,它看起来基本上是这样做的。有点烦人。幸运的是ely很快发现我的整个方法很愚蠢,并且能够将其全部删除,但仍然…;)是的,就我个人而言,我会尽量不让字符串出现在我的模板内容中。但是如果你必须这样做,上述方法似乎是目前针对特定问题的最简单的解决方案。而且它有点向前兼容,假设我们将n通常能够将字符串文本作为模板参数传递…是的,同意:)注意,模板将由指针参数化,即它们的地址,而不是它们的内容。因此,如果您在不同的函数中编写相同的代码(即使用
a
b
的不同实例),您将得到不同的模板实例化。
#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;