类中的模板函数

Template function in class

本文关键字:函数      更新时间:2023-10-16

我不知道该怎么办。我总是通过使用简单的类和简单的模板函数来得到错误。我阅读了所有其他解决方案,但它们对我没有帮助。

在其他一些类旁边,我有一个简单的类Data:

class Data{
public:
    template <class T>
    T dat();
    int id;
    union{
        char c;
    int i;
    double d;
    };
};

和函数dat:

template <class T>
T Data::dat(){
    if(id == 1) return i;
    if(id == 2) return d;
    if(id == 3) return c;
}

正如你所看到的,我想检查id并返回int、double或char。现在我尝试在主函数中打印值,如下所示:

Data test;
test.id=1;
test.i = 12;
cout<<test.dat();

但我总是收到这样的错误信息:

Error: Could not find a match for Data::dat<Data::T>() needed in main(int, char**).

问题出在哪里??

感谢

准确地说,您希望函数的返回类型取决于它是对象中的id字段;换句话说,动态地。模板在编译时解析,因此它们不能在这里帮忙。你必须归还类似的东西支持这种动态的boost::variantboost::any打字。

使用此:

cout<<test.dat<int>();

dat()没有涉及T的参数,因此编译器无法从调用中推断出T,必须显式提供,例如:

cout << test.dat<int>();

另外,请记住,必须在头文件中实现dat()

我不知道该怎么办。我总是在使用一个简单的类和一个简单模板函数时出错。我阅读了所有其他解决方案,但它们对我没有帮助。

在我看来,你想建立一个受歧视的联盟。

您的实现不起作用,因为模板函数的返回类型是在编译时确定的(即,在您设置id中的值并尝试调用该函数之前)

解决方案:

class Data
{
    enum value_type {
        int_val, char_val, double_val
    } discriminator; // private (the user doesn't see this)
                     // this replaces your id
    union{
        char c;
        int i;
        double d;
    } value;
public:
    class wrong_type_error: public std::logic_error
    {
    public:
        wrong_type_error(const std::string& msg): std::logic_error(msg) {}
    };
    explicit Data(const char c)
    : discriminator(Data::char_value)
    , value.c(c)
    {
    }
    explicit Data(const int i)
    : discriminator(Data::int_value)
    , value.i(i)
    {
    }
    explicit Data(const double d)
    : discriminator(Data::double_value)
    , value.d(d)
    {
    }
    // don't put this here: int id;
    // this part can be optimized to simpler (more idiomatic) code
    template<typename T> T get() const; // undefined
    template<> int get() const {
        if(discriminator != Data::int_val)
            throw wrong_type_error("Cannot return a int from Data instance");
        return value.i;
    }
    template<> char get() const {
        if(discriminator != Data::char_val)
            throw wrong_type_error("Cannot return a char from Data instance");
        return value.c;
    }
    template<> double get() const {
        if(discriminator != Data::double_val)
            throw wrong_type_error("Cannot return a double from Data instance");
        return value.d;
    }
};

客户代码:

Data test(10.5);
cout<<test.get<double>();

话虽如此,根据您的需要,您应该考虑使用boost::变体或boost::任何情况。

VS2012表示"错误C2783:"T数据::dat(void)":无法推导出"T"的模板参数

你只需要告诉函数dat什么是T

cout<<test.dat<int>();

如果您传递一个模板化参数,则可以推断出模板类型,但它无法猜测返回类型。