gpt4 book ai didi

c++ - 返回类型为 auto 的函数

转载 作者:行者123 更新时间:2023-11-28 00:20:03 24 4
gpt4 key购买 nike

我正在尝试创建一个名为 variant 的变量类型(有点像 VisualBasic 中的变量类型),它可以在其中更改变量类型(不是真的,但它会更改将返回的变量类型)。这是我的代码:

#include <string>
using namespace std;

class Variant{
private:
int int_v;
char char_v;
bool bool_v;
string string_v;

char type;

public:
void set(int);
void set(char);
void set(bool);
void set(string);

auto get();

Variant();
};

Variant::Variant(){
int_v = 0;
char_v = ' ';
bool_v = false;
string_v = "";
type = ' ';
}

void Variant::set(int value){
int_v = value;
char_v = ' ';
bool_v = false;
string_v = "";
type = 'i';
}

void Variant::set(char value){
char_v = value;
int_v = 0;
bool_v = false;
string_v = "";
type = 'c';
}

void Variant::set(bool value){
bool_v = value;
int_v = 0;
char_v = ' ';
string_v = "";
type = 'b';
}

void Variant::set(string value){
string_v = value;
int_v = 0;
char_v = ' ';
bool_v = false;
type = 's';
}

auto Variant::get(){
if(type == 'i') return int_v;
else if(type == 'c') return char_v;
else if(type == 'b') return bool_v;
else if(type == 's') return string_v;
else return -1;
}

int main(int argc, char *argv[]){

return 0;
}

这段代码应该做的是这样的:

#include <iostream>
#include "Variant.h"
using namespace std;

int main(int argc, char *argv[]){

Variant var;
var.set(5); //set var to 5
cout<<var.get()<<endl; //print var (5)
var.set('a'); //set var to 'a'
cout<<var.get()<<endl; //print var (a)
var.set(true); //set var to true
cout<<var.get()<<endl; //print var (true)
var.set("Hello, World!"); //set var to "Hello, World!"
cout<<var.get()<<endl; //print var (Hello, World!)

return 0;
}

但是 g++ 告诉我:

Variant.h:17:12: error: ISO C++ forbids declaration of ‘get’ with no type [-fpermissive]
auto get();
^
Variant.h:17:12: error: storage class specified for ‘get’

感谢所有帮助!谢谢!

最佳答案

返回类型必须在编译时可推导,类似于模板参数。该函数不能返回不同的类型,具体取决于运行时属性,例如变体当前包含的内容。

除了以下变体,你真的没有太多选择:

template<typename T>
T get() const;

调用时必须指定模板参数。 (我看不出返回一个 tuple 然后不得不调用 get<int> 有什么好处...)

这是更完整的示例代码:

// In class definition
template<typename T> T get() const;

// Outside
template<> char Variant::get<char>() const { return char_v; }
template<> int Variant::get<int>() const { return int_v; }
template<> bool Variant::get<bool>() const { return bool_v; }
template<> string Variant::get<string>() const { return string_v; }

关于c++ - 返回类型为 auto 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27976556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com