具有依赖于实现的成员函数类型的多个静态接口

multiple static interfaces with implementation-dependent type of member function

本文关键字:静态 接口 类型 成员 依赖于 实现 函数      更新时间:2023-10-16

>我有两个接口,我想与CRTP一起使用以实现静态多态性。其中一个包含的函数,其签名中的类型取决于实现。

这个问题看起来像这里问的没有解决方案。我想出的解决方案包括一个定义类型的附加模板化结构。然后,此模板专用于实现,避免"无效使用不完整类型"错误。

这是我的代码

#include <iostream>
#include <memory>
template<class impl1>
struct Interface1 {
    double foo() { return static_cast<impl1*>(this)->fooimpl();}
};
template<class impl1, class impl2>
struct typeHelp;
template<class impl1, class impl2>
struct Interface2 {
    void bar(typename typeHelp<impl1,impl2>::type value) {
        static_cast<impl2*>(this)->barimpl(value);
    }
};
//Implementation2 pre declaration
template<class impl1>
struct Implementation2;
//Partial specialization of templated typeHelp
template<class impl1>
struct typeHelp<impl1, Implementation2<impl1>> {
    using type = int;
};
//Implementation2
template<class impl1>
struct Implementation2 : public Interface2<impl1, Implementation2<impl1>> {
    std::shared_ptr<Interface1<impl1>> imp1;
    void barimpl(typename typeHelp<impl1,Implementation2>::type value) {
        std::cout << imp1->foo() << " " << value << std::endl;
    }
};
//Implementation1
struct Implementation1 : public Interface1<Implementation1> {
    double fooimpl() {return 0.;}
};
int main()
{
    Implementation2<Implementation1> obj;
    obj.imp1 = std::make_shared<Implementation1>();
    obj.bar(4);
}

我不喜欢这段代码的是 Interface2 和类型帮助依赖于模板参数 impl1。这适用于我的特定情况,其中 Implementation2 是相对于 impl1 模板化的,但如果 Implementation2 不是,则不会。我想知道这个问题是否有更通用和优雅的解决方案。

我的错; 多搜索一点,我就会找到答案。在此链接中,Andy G 指出,可以使用模板化类来专门化类模板。结果比以前更干净

#include <iostream>
#include <memory>
//Interface1.hpp
template<class impl1>
struct Interface1 {
    double foo() { return static_cast<impl1*>(this)->fooimpl();}
};
//Interface2.hpp
template<class impl2>
struct typeHelp;
template<class impl2>
struct Interface2 {
    void bar(typename typeHelp<impl2>::type value) {
        static_cast<impl2*>(this)->barimpl(value);
    }
};
//Implementation2.hpp
template<class impl1>
struct Implementation2;
//specialization of typeHelp with templated class
template<class impl1>
struct typeHelp<Implementation2<impl1>> {
    using type = int;
};
//Actual implementation of Implementation2
template<class impl1>
struct Implementation2 : public Interface2<Implementation2<impl1>> {
    std::shared_ptr<Interface1<impl1>> imp1;
    void barimpl(typename typeHelp<Implementation2<impl1>>::type value) {
        std::cout << imp1->foo() << " " << value << std::endl;
    }
};
//Implementation1.hpp
struct Implementation1 : public Interface1<Implementation1> {
    double fooimpl() {return 0.;}
};
//Main.hpp
int main()
{
    Implementation2<Implementation1> obj;
    obj.imp1 = std::make_shared<Implementation1>();
    obj.bar(4);
}