首页 > 解决方案 > Call static function of specialize template with base class of type T

问题描述

I need to write Stream class with a template Write function to accept any type and write it to stream.

I write a Stream class and a StreamWriter to partially specialize Write function, but compiler can't find static function of StreamWriter with base class of AInt class.

template<typename T>
class AType {
public:
   T rawValue;
    void Add(T v) { rawValue += v; }
    void Sub(T v) { rawValue += v; }
    void Mul(T v) { rawValue *= v; }
    void Mod(T v) { rawValue %= v; }
};

class AInt : public AType<int> {
public:
    using AType<int>::Add;
    using AType<int>::Sub;
    using AType<int>::Mul;
    using AType<int>::Mod;
};

class AFloat : public AType<float> {
public:
    using AType<float>::Add;
    using AType<float>::Sub;
    using AType<float>::Mul;
};
class AStream;

template<typename T>
class AStreamWriter {
public:
    static bool Write(AStream *stream, T v);
};

class AStream {
public:
    template<typename T>
    bool Write(T v) {
        return AStreamWriter<T>::Write(this, v);
    }
};

template<typename T>
class AStreamWriter<AType<T>> {
public:
    static bool Write(AStream *stream, AType<T> v) {
        //Do somethings
        return true;
    }
};

int main() {
    AInt x{10};
    AStream stream;
    stream.Write(x); //Error, Compiler can't find AStreamWriter<AInt>::Write
}

Is there any way to fix this problem?

标签: c++templates

解决方案


您的专业化与(您称为,而不是)AStreamWriter<AType<T>>无关。AStreamWriter<AInt>AStreamWriter<AInt>::Write(AStream*, AInt)AStreamWriter<AType<int>>::Write(AStream*, AType<int>)

重载或简单的模板函数可能是另一种选择......

template<typename T>
static bool Write(const AType<T>&) { return true; }

推荐阅读