代码之家  ›  专栏  ›  技术社区  ›  Utku Ufuk

如何在将模板转换为任意类型时避免编译器错误[重复]

  •  0
  • Utku Ufuk  · 技术社区  · 6 年前

    我正在尝试使用模板读取任意图像 std::vector 类型如下:

    #include <map>
    #include <vector>
    #include <string>
    
    using namespace std;
    
    class Reader
    {
        public:
            static void readShorts(string path, vector<short>& buffer)
            {
                // read short buffer
            }
    
            static void readChars(string path, vector<char>& buffer)
            {
                // read char buffer
            }
    };
    
    template <typename T>
    class GenericReader
    {
        public:
            static void read(string path, T& buffer)
            {
                if (typeid(buffer) == typeid(vector<char>))
                {
                    Reader::readChars(path, buffer);
                }
                else if (typeid(buffer) == typeid(vector<short>))
                {
                    Reader::readShorts(path, buffer);
                }
            }
    };
    
    template <typename T>
    class Container
    {
        private:
            map<int, T> images;
    
        public:
            void readImage(string path, int imageId)
            {
                GenericReader<T>::read(path, images[imageId]);
            }
    };
    
    int main(int argc, char **argv)
    {
        Container<vector<char>> container;
        container.readImage("some/path/img.tif", 0);
    }
    

    但我得到以下错误:

    error C2664 : 'void Reader::readShorts(std::string,std::vector<short,std::allocator<_Ty>> &)' : cannot convert argument 2 from 'T' to 'std::vector<short,std::allocator<_Ty>> &'
    

    我了解问题的发生是因为我创建了 Container 类与 vector<char> 类型,所以最终 readShorts 的成员函数 Reader 调用。但这不是使用模板的目的吗?我在想,在这种情况下,我会得到一个运行时错误,而不是编译器错误。

    我的问题的第二部分是,有没有一种优雅的方式来做我想在这里实现的事情?如果我做错了什么事,我会接受不同的方法。

    顺便说一下,我知道问题标题不太清楚,请随意编辑。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Bartek Banachewicz    6 年前

    自从你 GenericReader 完全不是通用的(因为它只在两个特定类型上工作),并且只委托给特定的实现,一个更简单的方法是简单地使用重载:

    void readVector(string path, vector<short>& buffer)
    {
        // read short buffer
    }
    
    void readVector(string path, vector<char>& buffer)
    {
        // read char buffer
    }
    

    然后:

    void readImage(string path, int imageId)
    {
        readVector(path, images[imageId]);
    }