在派生类中专门化基类的模板化成员函数

时间:2016-10-01 16:32:40

标签: c++ templates inheritance

TL; DR;

编译以下代码以两个未解析的外部结束。

问题

有没有办法在基类中有一个未定义的模板化成员函数,并且该函数部分地专门用于派生的classe,所以部分特化将限制在它定义的派生类中?

说明

正如您所看到的,serial_portliquid_crystal都来自stream基类。 stream类将提供统一的接口,以便将文本发送到不同的外围设备。从stream派生的每个类都必须实现print(char)函数,该函数将处理与外设的低级通信。除此之外,还有一个未定义的模板化打印版本,可以专门用于用户可能想要打印的任何自定义类型。

stream类具有operator <<的模板化定义,用于将数据写入流中。该操作员将调用stream::print来处理实际打印。正如您所看到的那样print(const char*)print(fill)已经定义,因为我希望它们出现在stream的每个派生类中。

现在出现了引入错误的部分

我要与之通信的外围设备有一些基本命令(LCD:将光标移动到x,y坐标,串口:将波特率设置为x),它们之间不可互换,这意味着LCD不知道如何更改波特率并且串口没有可以移动到特定坐标的光标。我想通过operator <<传递命令,就像我使用fill一样。每个命令都是一个包含命令所需数据的新结构,并且会有print的专用版本来处理它们。

这在理论上有效但在编译期间失败,因为print的专用版本在派生类中定义,但operator <<stream类中定义。当我将命令传递给流时,链接器在print内寻找stream的专门定义,当然它会失败,因为那些根本就不存在。

我怎么能克服这个错误? 我使用的是Visual Studio 15 Preview 4,但我没有更改任何编译器标志。

消息来源

#include <iostream>

class stream
{
public:
    struct fill
    {
        int n;
        char ch;
    };

    stream()
    {}

    virtual ~stream()
    {}

    template <typename T>
    stream& operator << (T t)
    {
        this->print(t);
        return *this;
    }

protected:
    virtual void print(char) = 0;

    template <typename T>
    void print(T);
};

template <>
void stream::print<const char*>(const char* str)
{
    while (*str != '\0')
        this->print(*(str++));
}

template <>
void stream::print<stream::fill>(stream::fill f)
{
    while (f.n > 0)
    {
        this->print(f.ch);
        f.n--;
    }
}

class serial_port : public stream
{
public:
    struct set_baudrate
    {
        int baud;
    };

    using stream::stream;

private:
    void print(char c) override
    {
        // TODO: print to the actual serial port
        std::cout << c;
    }

    template <typename T>
    void print(T t)
    {
        stream::print<T>(t);
    }
};

template <>
void serial_port::print<serial_port::set_baudrate>(serial_port::set_baudrate)
{
    this->print("set_baudrate");
}

class liquid_crystal : public stream
{
public:
    struct move
    {
        int x;
        int y;
    };

    using stream::stream;

private:
    void print(char c) override
    {
        // TODO: print to a character LCD
        std::cout << c;
    }

    template <typename T>
    void print(T t)
    {
        stream::print<T>(t);
    }
};


template <>
void liquid_crystal::print<liquid_crystal::move>(liquid_crystal::move)
{
    this->print("move");
}

int main()
{
    liquid_crystal lcd;
    lcd << liquid_crystal::move{ 1, 2 };
    serial_port serial;
    serial << serial_port::set_baudrate{ 9600 };
}

修改

查看compiler output时问题更明显,链接器正在寻找void stream::print<liquid_crystal::move>(liquid_crystal::move)void stream::print<serial_port::set_baudrate>(serial_port::set_baudrate),但功能签名应为void liquid_crystal::print<liquid_crystal::move>(liquid_crystal::move)void serial_port::print<serial_port::set_baudrate>(serial_port::set_baudrate)

2 个答案:

答案 0 :(得分:0)

main中,行:

lcd << liquid_crystal::move{ 1, 2 };

调用:

stream::operator<< <liquid_crystal::move>(liquid_crystal::move)

然后调用:

stream::print<liquid_crystal::move>(liquid_crystal::move)

stream::print函数仅针对const char*stream::fill类型定义。

未使用liquid_crystal::print函数,因为它不是stream::print的覆盖(它隐藏了stream::print类中的liquid_crystal。要使用stream thisstream*而不是liquid_crystal*)从stream::print访问它,operator<<必须是虚拟的。但在这种情况下,这是不可能的,因为它是一个模板函数。

通常,虚拟模板功能设计问题的解决方案通常并不简单。但在这种特定情况下,最简单的方法可能是复制每个派生类中的stream::operator<<。但是,在调用void func(stream& s) { s << liquid_crystal::move{ 1, 2 }; } int main() { liquid_crystal lcd; func(lcd); } 的情况下,它不起作用,例如:

topLevelMessageImage.setOnClickListener(v -> {

                    ParseQuery<ParseObject> imageQuery = new ParseQuery<>(ParseConstants.CLASS_YEET);
                    imageQuery.whereEqualTo(ParseConstants.KEY_OBJECT_ID, topLevelCommentObject.getObjectId());
                    imageQuery.findInBackground((user, e2) -> {
                        if (e2 == null) for (ParseObject userObject : user) {

                            if (userObject.getParseFile("image") != null) {
                                String imageURL = userObject.getParseFile("image").getUrl();
                                Log.w(getClass().toString(), imageURL);

                                // Asynchronously display the message image downloaded from Parse
                                if (imageURL != null) {

                                    Intent intent = new Intent(getApplicationContext(), MediaPreviewActivity.class);
                                    intent.putExtra("imageUrl", imageURL);
                                    this.startActivity(intent);

                                }

                            }
                        }
                    });
                });

答案 1 :(得分:0)

最佳解决方案是每个类自己定义operator<<。但是,如果这是不可能的,可以滥用SFINAE和动态铸造来达到预期的效果。

建议您在最终产品中使用此功能。我只是在这里发布它,希望有一个比我更有知识的人能够找到一种方法来使这个工作没有dynamic_cast,而不会引入可能导致未定义行为的代码。

#include <iostream>
#include <type_traits>

// -----

// void_t definition.  If your compiler has provisional C++17 support, this may already be
//  available.
template<typename...>
struct make_void { using type = void; };

template<typename... T>
using void_t = typename make_void<T...>::type;

// -----

// SFINAE condition: Is argument a stream command?

class stream;

template<typename T, typename = void>
struct is_stream_command : std::false_type
{};

template<typename T>
struct is_stream_command<T, void_t<typename T::command_for>> :
    std::integral_constant<bool, std::is_base_of<stream, typename T::command_for>::value ||
                                 std::is_same<stream, typename T::command_for>::value>
{};

// -----

class stream
{
public:
    // Stream command type.  Used as parent class for actual commands.
    // Necessary for version of print() that handles stream commands.
    // Not needed for SFINAE.
    // If used, each command will need a constructor.
    struct command
    {
        using command_for = stream;
        // This typedef should be defined in each command, as the containing class.
        // If command is valid for multiple classes, this should be their parent class.
        // Used for SFINAE.

        virtual ~command() = default;
    };

    struct fill : command
    {
        int n;
        char ch;
        using command_for = stream;

        fill(int n, char ch) : n(n), ch(ch) {}
    };

    stream()
    {}

    virtual ~stream()
    {}

    // Called for stream commands.  Solves the issue you were having, but introduces a
    //  different issue: It casts "this", which can cause problems.
    // Tied with a version of stream::print() that handles commands.
    template<typename T>
    typename std::enable_if<is_stream_command<T>::value, stream&>::type
    operator<<(T t)
    {
        static_cast<typename T::command_for*>(this)->print((stream::command*) &t);
        return *this;
    }

    // Called for other output.
    template<typename T>
    typename std::enable_if<!is_stream_command<T>::value, stream&>::type
    operator<<(T t)
    {
        this->print(t);
        return *this;
    }

protected:
    virtual void print(char) = 0;

    virtual void print(stream::command* com);

    template <typename T>
    void print(T);
};

template <>
void stream::print<const char*>(const char* str)
{
    while (*str != '\0')
        this->print(*(str++));

    std::cout << std::endl; // For testing.
}

template <>
void stream::print<stream::fill>(stream::fill f)
{
    std::cout << "fill "; // For testing.

    while (f.n > 0)
    {
        this->print(f.ch);
        f.n--;
    }

    std::cout << std::endl; // For testing.
}

// Version of print() which handles stream commands.
// Solves problem introduced by operator<<() for commands, but introduces its own problem:
//  dynamic casting.
void stream::print(stream::command* com) {
    if (dynamic_cast<stream::fill*>(com)) {
        std::cout << "Valid command: "; // For testing.
        this->print(*(dynamic_cast<stream::fill*>(com)));
    } else {
        // Handle as appropriate.
        std::cout << "Invalid command." << std::endl;
    }
}

// -----

class serial_port : public stream
{
public:
    struct set_baudrate : stream::command
    {
        int baud;
        using command_for = serial_port;

        set_baudrate(int baud) : baud(baud) {}
    };

    using stream::stream;

private:
    void print(char c) override
    {
        // TODO: print to the actual serial port
        std::cout << c;
    }
    void print(stream::command* com) override;

    template <typename T>
    void print(T t)
    {
        stream::print<T>(t);
    }

    // Necessary to allow stream::operator<<() to call private member function print().
    template<typename T>
    friend typename std::enable_if<is_stream_command<T>::value, stream&>::type
    stream::operator<<(T t);
};

template <>
void serial_port::print<serial_port::set_baudrate>(serial_port::set_baudrate)
{
    this->print("set_baudrate");
}

void serial_port::print(stream::command* com) {
    if (dynamic_cast<serial_port::set_baudrate*>(com)) {
        std::cout << "Valid command: "; // For testing.
        this->print(*(dynamic_cast<serial_port::set_baudrate*>(com)));
    } else {
        // Invalid commands fall through to parent class, in case they're valid for any
        //  stream.
        this->stream::print(com);
    }
}

// -----

class liquid_crystal : public stream
{
public:
    struct move : stream::command
    {
        int x;
        int y;
        using command_for = liquid_crystal;

        move(int x, int y) : x(x), y(y) {}
    };

    using stream::stream;

private:
    void print(char c) override
    {
        // TODO: print to a character LCD
        std::cout << c;
    }
    void print(stream::command* com) override;

    template <typename T>
    void print(T t)
    {
        stream::print<T>(t);
    }


    // Necessary to allow stream::operator<<() to call private member function print().
    template<typename T>
    friend typename std::enable_if<is_stream_command<T>::value, stream&>::type
    stream::operator<<(T t);
};

template <>
void liquid_crystal::print<liquid_crystal::move>(liquid_crystal::move)
{
    this->print("move");
}

void liquid_crystal::print(stream::command* com) {
    if (dynamic_cast<liquid_crystal::move*>(com)) {
        std::cout << "Valid command: "; // For testing.
        this->print(*(dynamic_cast<liquid_crystal::move*>(com)));
    } else {
        // Invalid commands fall through to parent class, in case they're valid for any
        //  stream.
        this->stream::print(com);
    }
}

// -----

int main()
{
    liquid_crystal lcd;
    lcd << 'a' << " " << liquid_crystal::move{ 1, 2 };
    serial_port serial;
    serial << 'a' << " " << serial_port::set_baudrate{ 9600 };

    std::cout << "Are they valid commands?" << std::endl;
    std::cout << std::boolalpha;
    std::cout << "stream::fill, for serial_port: ";
    serial << stream::fill{ 3, 'a' };
    std::cout << "stream::fill, for liquid_crystal: ";
    lcd << stream::fill{ 3, 'a' };

    std::cout << "serial_port::set_baudrate, for serial_port: ";
    serial << serial_port::set_baudrate{ 9600 };
    std::cout << "serial_port::set_baudrate, for liquid_crystal: ";
    lcd << serial_port::set_baudrate{ 9600 };

    std::cout << "liquid_crystal::move, for serial_port: ";
    serial << liquid_crystal::move{ 1, 2 };
    std::cout << "liquid_crystal::move, for liquid_crystal: ";
    lcd << liquid_crystal::move{ 1, 2 };
}

这将有以下输出:

a b
Valid command: move
a b
Valid command: set_baudrate
Are they valid commands?
stream::fill, for serial_port: Valid command: fill aaa
stream::fill, for liquid_crystal: Valid command: fill aaa
serial_port::set_baudrate, for serial_port: Valid command: set_baudrate
serial_port::set_baudrate, for liquid_crystal: Invalid command.
liquid_crystal::move, for serial_port: Invalid command.
liquid_crystal::move, for liquid_crystal: Valid command: move

我不喜欢这个解决方案,因为它依赖于dynamic_cast。但是,我发现错误的解决方案通常比没有解决方案更好,因为它可以帮助您找到良好的解决方案。这解决了链接问题,理想情况下可以用作不需要任何投射的解决方案的基础。