【问题标题】:Is it possible to create an array with subscripts of variable type through the template?是否可以通过模板创建带有变量类型下标的数组?
【发布时间】:2020-10-18 00:26:54
【问题描述】:

可以这样使用

str<int> = "int";
num<double> = 2;
cout << str<int> << endl; // output "int"
cout << num<double> << endl; // output 2

【问题讨论】:

    标签: c++ templates template-meta-programming c++20


    【解决方案1】:

    是的,如下声明strnum

    template <typename>
    std::string str;
    
    template <typename>
    int num;
    

    是模板变量,从 C++14 开始可用。

    但要考虑到所有str 变量的类型为std::string,并且所有num 变量的类型为int

    正如 Davis Herrings 所指出的,使用专业化(部分或完全专业化)可以缓解这个问题。例如,如果你希望str&lt;some-type&gt;,对于泛型类型some-type,是一个整数值,除了str&lt;int&gt;,它必须是std::string,你可以如下声明它

    template <typename>
    int str;
    
    template <>
    std::string str<int>;
    

    以下是完整的编译示例

    #include <iostream>
    
    template <typename>
    std::string str;
    
    template <typename>
    int num;
    
    int main ()
     {
       str<int> = "int";
       num<double> = 2;
    
       std::cout << str<int> << std::endl; // output "int"
       std::cout << num<double> << std::endl; // output 2
     }
    

    【讨论】:

    • @nullptr 我其实对为什么你需要这个很感兴趣。它解决了什么问题?
    • @cigien 我尝试创建一个通用的to_string函数,可以将标准库容器转换为字符串,我需要对不同的容器使用不同的分隔符,例如输出std::array到[1, 2,3],转换 std ::vector 输出为 {1;2;3}。
    • @cigien 我想要一个单一版本的 to_string 来处理多种容器,所以我需要一个将类型作为参数的容器来存储这些不同的分隔符。
    • 您可以特化(甚至部分特化!)变量模板在某些情况下具有不同的类型(与可以重载但必须匹配其(显式)特化的函数模板不同)。
    • @nullptr - 可能并不完美,但是...而不是typename,模板参数可以是template &lt;typename...&gt; classtemplate &lt;template &lt;typename...&gt; class&gt; std::string str; 之类的东西。应该与几乎所有 STL 容器兼容(但不幸的是,不兼容 std::array)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多