代码之家  ›  专栏  ›  技术社区  ›  Alexey Subbota

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

  •  2
  • Alexey Subbota  · 技术社区  · 7 年前

    我想用可变的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 回复  |  直到 7 年前
        1
  •  3
  •   Michael Kenzel    7 年前

    错的是 [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
  •  3
  •   Vittorio Romeo    7 年前

    这与正在使用的模板参数无关 -字符串不能简单地用作模板参数(直到 P0732 -这被接受了——变成了现实)。

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

    也会失败。 live example on godbolt.org

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

        3
  •  2
  •   amin    7 年前

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

    #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;