【问题标题】:Specialization of variadic template function可变参数模板函数的特化
【发布时间】:2014-07-17 23:48:35
【问题描述】:

我正在尝试为我定义的任意数量的特定类型层次结构聚合成员变量的值。

使用可变参数模板函数很容易做到这一点。

当我尝试将调用此模板的函数的名称作为字符串作为第一个参数传入时,我运气不佳。 这很难解释,所以下面是一些我必须演示我正在尝试做的代码。

尝试编译此结果: 错误 C2993:“std::string”:非类型模板参数“str”的非法类型

我试图做的事情是不可能的吗?还是我只是以错误的方式处理它?

std::ostringstream output;
int objCounter = 0;

void set_results() {
    output << "\n" << std::endl;
}

template <typename obj,  typename ...objs>
void set_results(obj objHead, objs... objTail) {
    ++objCounter;
    output << "Argument (" << objCounter << ") \t" << objHead.bytes << std::endl;
    set_results(objTail...);
}

template <std::string str, typename ...objs>
void set_results(std::string objHead, objs... objTail) {
    output << "Leaf Function: " << objHead << std::endl;
    set_results(objTail...);
}

class objDep {
public:
    int bytes;
    objDep(int b) : bytes(b) {}
};


int _tmain(int argc, _TCHAR* argv[])
{
    objDep one(1);
    objDep two(2);
    objDep three(3);
    objDep four(4);

    set_results(std::string("main"), one, two, three, four);

    std::cout << output.str() << std::endl;

    return 0;
}

【问题讨论】:

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


    【解决方案1】:

    改变

    template <std::string str, typename ...objs>
    void set_results(std::string objHead, objs... objTail) {
        output << "Leaf Function: " << objHead << std::endl;
        set_results(objTail...);
    }
    

    到:

    template <typename ...objs>
    void set_results(std::string objHead, objs... objTail) {
        output << "Leaf Function: " << objHead << std::endl;
        set_results(objTail...);
    }
    

    您不能拥有std::string 类型的模板参数,无论如何,您完全不清楚您希望str 代表什么。

    请注意,函数模板不能部分特化。通过此替换,您将拥有两个 重载 set_results。将选择带有std::string 参数的那个,因为它更专业。

    【讨论】:

      【解决方案2】:

      模板参数列表中根本不需要std::string str

      template <typename ...objs>
      void set_results(std::string objHead, objs... objTail)
      

      没用过,首先,非类型模板参数只能是整数(intlong等)、枚举或函数符号。

      模板指定函数或类的泛型方式。说:

      template <typename obj, typename ...objs>
      void set_results(obj objHead, objs... objTail)
      

      意思是“给定某种类型,称之为obj,以及一些类型列表,称之为objsset_results取一个obj类型的值和一系列objs类型的值,并返回void”。

      【讨论】:

        猜你喜欢
        • 2017-10-15
        • 1970-01-01
        • 2021-07-26
        • 2011-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-03
        相关资源
        最近更新 更多