从左值推导出模板返回类型?

Res*_*ion 5 c++ templates

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

template<class T> T getValue(const char *key) const;
Run Code Online (Sandbox Code Playgroud)

T从内部存储返回值,它存储在key(并且可能已经作为类型 T )。

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

int value = getValue<int>("myKey");
Run Code Online (Sandbox Code Playgroud)

而我希望它做的是从上下文中推断出模板参数,特别是lvalue像这样:

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

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

Cre*_*ris 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;

}
Run Code Online (Sandbox Code Playgroud)

你可以在这里尝试一下