从左值开始的模板返回类型扣除?

时间:2015-09-13 20:53:48

标签: c++ templates

这可能是一个愚蠢的问题,但我想澄清一点。假设我有一个类似的模板函数:

template<class T> T getValue(const char *key) const;

从内部存储返回T的值,它存储在key下(可能已经是T类型)。

现在为了使用它,我需要在函数调用中指定模板返回类型T,例如:

int value = getValue<int>("myKey");

虽然我希望它做的是从上下文中推导出模板参数,特别是lvalue,如下所示:

int value = getValue("myKey"); //getValue<int>() is instantiated with int being deduced automatically from lvalue

但我猜这不可能,但我为什么这么模糊。我知道使用auto会使编译器无法推断出模板类型,但为什么会这样呢?

1 个答案:

答案 0 :(得分:3)

模板实例化只能从给定模板化对象的参数中推导出它的参数(在这种情况下是函数)所以不,变量类型在推导中无关紧要,你要么必须为函数提供类型为T的伪参数,要么像在倒数第二个脚本代码(getValue<int>(...))中那样硬编码。

在评论中提供了使用类型推导的可能解决方法:

#include <iostream>

namespace byte_read {
    //this is a hack to deduce the type using implicit conversion
    struct type_converter {
        const char* buffer;

        template<typename T>
            operator T() {
            std::cout << "implicit convertion from " << typeid(buffer).name() 
                << " to " << typeid(T).name() << std::endl;
            //casting memory to the desired type
            return static_cast<T>(*buffer);
        }
    };
    type_converter getValue(const char * buffer) {
        //here buffer is implicitly converted to T type using the operator T()
        return {buffer};
    }

}
using namespace byte_read;

int main()
{
    char buffer[]{0,1,0,0 //int 256 encoded
                  ,97      //char 'a' encoded
                 };
    //pointer to read the buffer sequentialy
    char* pos = buffer;
    //pointer used to count the bytes readed
    char* last_pos = pos;

    int int_256 = getValue(pos);
    pos+=sizeof(int);
    std::cout << int_256 << " bytes readed :" << pos - last_pos << std::endl;

    last_pos = pos;
    char char_a = getValue(pos);
    pos+=sizeof(char);
    std::cout << char_a << " bytes readed :" << pos - last_pos << std::endl;

}

您可以尝试here

相关问题