简体   繁体   English

新构造的对象作为默认模板函数参数

[英]Newly constructed object as default template function argument

Test::load should load data (described either by name or index) into passed reference. Test::load应该将数据(通过名称或索引描述)加载到传递的引用中。 As third parameter there is a default value in case of loading fail (data are loaded from file). 作为第三个参数,在加载失败的情况下存在默认值(数据从文件加载)。

struct Test
{
    template <typename ValueType, typename DefaultValueType>
    void load(const char * c, ValueType & a, DefaultValueType b)
    {
        std::cout << "1";
    }

    template <typename ValueType, typename DefaultValueType>
    void load(int i, ValueType & a, DefaultValueType b)
    {
        std::cout << "2";
    }
};

I need both ValueType and DefaultValueType because of my special need for strings and custom types. 我需要ValueTypeDefaultValueType因为我特别需要字符串和自定义类型。 Problem occurs when I want to use default constructed type as default third argument (in const char * version) deduced from ValueType. 当我想使用默认构造类型作为从ValueType推导出的默认第三个参数(在const char *版本中)时,会出现问题。

template <typename ValueType, typename DefaultValueType>
void load(const char * c, ValueType & a, DefaultValueType b = ValueType())
{
    std::cout << "1";
}

I get expects 3 arguments error (vs2010). 我得到expects 3 arguments错误(vs2010)。

Why it doesn't work? 为什么它不起作用? I need to do workaroud to make this work. 我需要做workaroud来完成这项工作。


Here is full "working" code if anyone is interested to play around 如果有人有兴趣玩,这里是完整的“工作”代码

#include <iostream>

struct Test
{
    template <typename ValueType, typename DefaultValueType>
    void load(const char * c, ValueType & a, DefaultValueType b/* = ValueType()*/)
    {
        std::cout << "1";
    }

    template <typename ValueType, typename DefaultValueType>
    void load(int i, ValueType & a, DefaultValueType b)
    {
        std::cout << "2";
    }

    //Workaround
    template<typename ValueType>
    void load(const char * c, ValueType & v)
    {
        load(c,v,ValueType());
    }
};

int main()
{
   Test t;
   float f;

   //This is standard behavior
   t.load("bar", f, 0.0f);

   //I want this to be possible call
   t.load("bar", f);
}

You are looking for partial template specialization . 您正在寻找部分模板专业化 However partial template specialization is possible only for classes and not for functions. 但是,部分模板专门化仅适用于类而不适用于函数。 For functions, you solve the issue through overloading, which is exactly what you have done in your workaround. 对于函数,您可以通过重载来解决问题,这正是您在变通方法中所做的。

Here is a writeup on why template functions have overloading rather than specialization. 这里是一个书面记录 ,为什么模板函数重载了,而不是专业化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM