从左值推导模板返回类型

Template return type deduction from lvalue?

本文关键字:返回类型      更新时间:2023-10-16

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

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

从存储在key下(可能已经是类型T)的内部存储器中返回值为T

现在为了使用这个,我需要在函数调用中指定模板返回类型T,例如:
int value = getValue<int>("myKey");

而我想让它做的是从上下文中推断模板参数,特别是lvalue,如下所示:

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

,但我猜这是不可能的,但我是相当模糊的原因。我知道使用auto将使编译器无法推断模板类型,但为什么这也是?

模板实例化只能从给定模板对象(本例中为函数)的参数中推断出其参数,因此不,变量类型在推断中无关紧要,您要么必须为函数提供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;
}

你可以在这里试试