提问者:小点点

是否可以将泛型变量改为特定的,或者用泛型变量的值初始化特定类型的变量?


#include <iostream>
#include <typeinfo>
#include <string>
#include <cstdlib>
using namespace std;

template <typename First>

class VerifyIfTrue{

    protected:
        First AG;
        int tries = 0;
        int vaalue;
        int RT;
        string whatis;
        string lie1;
        string lie2;

        VerifyIfTrue(string twhatis, string tlie1, string tlie2) : whatis(twhatis), lie1(tlie1), lie2(tlie2)
{input();}

        void input(){
            if(tries == 0){
            cout << "Tell me your " << whatis << "\n";}else{
            cout << "Come on, what's your " << whatis << "\n";}
            cin >> AG;

            if(typeid(AG).name() != typeid(int).name())
            {
                int x = 0;
                AG = x;
                cout << "Wrong type" << endl;
                ++tries;
                input();
            }else{
                int a = AG;
                positivetest(a);
            }
void positivetest(int RT){
            if(RT <=0)
            {
                cout << lie1 << "\n";
                if(tries == 0)
                {
                    ++tries;
                    cout << lie2 << "\n";

            }
            int y = 0;
            AG = y;
            ++tries;
            input();
            }else{
            vaalue = AG;
            }
        }
            }
...

我得到以下错误:

初始化中无法将“std::__cxx11::basic_string”转换为“int”

有办法解决这个问题吗?我想把AG变成一个int,这样它就可以被传递到int参数中,或者如果它是int,就可以被测试;或者能够将其值赋给int


共1个答案

匿名用户

如果constexpr(C++17)与std::is_same,则可以使用:

if constexpr (!std::is_same_v<int, First>) {
    int x = 0;
    AG = x;
    cout << "Wrong type" << endl;
    ++tries;
    input();
} else {
    int a = AG;
    positivetest(a);
}

相关问题