【问题标题】:Template class char*, return type of function const char*?模板类 char*,函数 const char* 的返回类型?
【发布时间】:2022-01-16 18:45:20
【问题描述】:

我有这个模板化的基类:

template <class V>
class ValueParam
{
public:
    virtual V convert(const char* f) const = 0;

protected:
    V val;
};

请注意,我可以存储一些类型为 V 的值 val,并且我有一个 convert 函数,当我在 ValueParam 对象上调用它时,它会自动返回正确的类型。

int 类型为 V 的示例:

class IntParam : public ValueParam<int>
{
public:
    IntParam(int i) { val = i; }

    int convert(const char* f) const override { return atoi(f); }
};

然后我们可以使用:

IntParam i(1234);       // The value of val is 1234
int x = i.convert("1"); // x will be 1

现在我在使用char* 作为我的类型V 时遇到了一个问题:

class StrParam : public ValueParam<char*>
{
public:
    StrParam(const char* str, size_t max_len)
    {
        val = new char[max_len + 1]{};
        strncpy(val, str, max_len + 1);
    }
    ~StrParam() { delete[] val; }

    char* convert(const char* f) const override { return f; } // Doesn't compile: f is const char*
};

我不想做任何 const 转换。

幸运的是,我不需要convert 的结果以任何方式可变。我可以将它的返回类型更改为可以编译的东西吗?

那会是什么类型?因为仅仅将其更改为virtual const V convert... 将意味着StrParam 中的返回类型将变为char* const convert...,这显然仍然不起作用。

【问题讨论】:

    标签: c++ c++11 templates


    【解决方案1】:

    您可以在返回类型的指向类型上添加const

    // for non-pointer type
    template <typename T>
    struct add_const_pointee { using type = T; };
    // for pointer type
    template <typename T>
    struct add_const_pointee<T*> { using type = const T*; };
    // helper type
    template <typename T>
    using add_const_pointee_t = typename add_const_pointee<T>::type;
    
    template <class V>
    class ValueParam
    {
    public:
        virtual add_const_pointee_t<V> convert(const char* f) const = 0;
    //          ^^^^^^^^^^^^^^^^^^^^^^
    protected:
        V val;
    };
    

    class StrParam : public ValueParam<char*>
    {
    public:
        StrParam(const char* str, size_t max_len)
        {
            val = new char[max_len + 1]{};
            strncpy(val, str, max_len + 1);
        }
        ~StrParam() { delete[] val; }
    
        const char* convert(const char* f) const override { return f; }
    //  ^^^^^
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多