Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何创建用户定义类型(String,int,SO)模板类对象C++_C++_Templates - Fatal编程技术网

如何创建用户定义类型(String,int,SO)模板类对象C++

如何创建用户定义类型(String,int,SO)模板类对象C++,c++,templates,C++,Templates,我正在努力让用户选择数据类型模板将创建为。由于模板类型必须在编译时定义,所以我必须指定数据类型template将使用egstring、int等,但这意味着我以后无法将其更改为int,即使我的模板支持它,也不能更改为string,因为template类对象被声明为string 请注意,您的说明没有要求更改类型,只是用户可以提前选择 当然,你可以用模板来解决这个问题 一个简单的例子: template<typename T> void interact() { std::vect

我正在努力让用户选择数据类型模板将创建为。由于模板类型必须在编译时定义,所以我必须指定数据类型template将使用egstring、int等,但这意味着我以后无法将其更改为int,即使我的模板支持它,也不能更改为string,因为template类对象被声明为string

请注意,您的说明没有要求更改类型,只是用户可以提前选择

当然,你可以用模板来解决这个问题

一个简单的例子:

template<typename T>
void interact()
{
    std::vector<T> collection;
    std::cout << "Enter five things\n";
    while (collection.size() < 5)
    {
        std::string input;
        if (std::cin >> input)
        {
            std::istringstream iss(input);
            T value {};
            if (iss >> value)
            {
                collection.push_back(value);
            }
            else
            {
                std::cout << "That was not a good thing. Try again.";
            }
        }
    }
    std::cout << "You gave me: ";
    for (const auto& i: collection)
    {
        std::cout << i << ' ';
    }
}

int main()
{
    for (;;)
    {
        std::cout << "What do you want you work with?\n";
        std::string selection;
        std::cin >> selection;
        if (selection == "string")
        {
            interact<string>();
            break;
        }
        else if (selection == "int")
        {
            interact<int>();
            break;
        }
        else
        {
            std::cout << "Does not exist. Try again.\n";
        }
    }
}

听起来像是一场灾难。你不能做你要求的事。你需要一种不同的方法来解决你真正的问题。。您试图实现什么?修改交互式提示以以下方式使用模板:•在请求启动容量之前,提示用户指定他们希望向量在数据O1中存储的数据类型,对于int O2,对于float O3,对于double O4,对于string O5,对于bool@Knight听起来您希望在int和std::string上运行哪种代码?你想在这里干什么?
$ ./app
What do you want you work with?
int
Enter five things
1 2 3 5 5
You gave me: 1 2 3 5 5

$ ./app
What do you want you work with?
string
Enter five things
hi ho here we go
You gave me: hi ho here we go