从左值推导模板返回类型
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;
}
你可以在这里试试
相关文章:
- 如何获取std::result_of函数的返回类型
- 奇怪的结构&GCC&clang(void*返回类型)
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 函数作为模板参数,是否对返回类型强制约束
- C++中函数的向量返回类型引发错误
- 检查函数返回类型是否与STL容器类型值相同
- 为什么返回类型中需要typename?C++
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 推导 std::vector::back() 的返回类型
- 在 c++ 中将函数返回类型指定为模板参数
- 使用 SWIG 更改生成的 CS 函数中的返回类型
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 基于返回类型的转换和过载扣除
- 当返回类型声明为 ListNode 时,我们是否可以返回 false<T>*