模板 class 根据它们的存在和优先级调用其他 classes 的一些命名函数

Template class to call some named function of other classes based on their presence and priority

我有 structs/class 这样的:

struct LD {                             //Login detail
        std::string username;
        std::string password;

        std::string toString() const {
        return "Username: " + username
        + " Password: " + password;
    }
};

struct UP {                          //User Profile
    std::string name;
    std::string email;

    ostream& pPrint(ostream& ost) const {
        ost << "Name: " << name
        << " Email: " << email;
        return ost;
    }

    std::string toString() const {
        return "NULLSTRING";
    }
};

我正在创建一个模板 pPrint class,它将调用 class 的 pPrint 函数(如果存在)。如果不可用,它将调用 class 的 toString 函数,如果它也不可用,它将打印 "NO print function"

优先级:- 1)p打印 2)到字符串 3)简单输出"NO print Function"

int main() {

    LD ld = { "And", "Ap" };
    UP  up = { "James Brannd", "jamens@goo.com" };

    // this should print "Name: James Email: jamens@goo.com"
    std::cout << PPrint <UP> (up) << std::endl;

    // this should print "Username: And Password: Ap"
    std::cout << PPrint <LD> (ld) << std::endl;
}

现在我已经创建了这个 class 如下:

template<typename T>
struct HaspPrintMethod
{
    template<typename U, std::ostream&(U::*)(std::ostream&) const> struct     SFINAE {};
    template<typename U> static char Test(SFINAE<U, &U::pPrint>*);
    template<typename U> static int Test(...);
    static const bool Has = sizeof(Test<T>(0)) == sizeof(char);
};

template <class T>
class PPrint {
    public:
    PPrint(T m)
    {
        CallPrint(m, std::integral_constant<bool,     HaspPrintMethod<T>::Has>());
    }
    void CallPrint(const T& m, std::true_type)
    {
        std::ostringstream  os;
        m.pPrint(os);
        buf = os.str();
    }
    void CallPrint(const T& m, std::false_type)
    {
        buf = m.toString();
    }
    std::string buf;
};
template <class T>
std::ostream& operator<<(std::ostream &os, pPrint<T> const &m)
{
    return os << m.buf;
}

但它不起作用 参考:Check if a class has a member function of a given signature

新要求:- 模板 Class 名称为 PPrint 我们要检测的功能是 1)pPrint 2)toString 3)if not this to "No func available"

pPrint 应检测到此原型:

ostream& pPrint(ostream& ost) const;

但是结构中的函数可以像这样:(不应该被检测到)

ostream& PPrint(ostream& ost) const; // case sensitive and same name as class name
ostream& pPrint(ostream& ost);  //without const specifier 

如何构建模板Class PPrint 来做?

我认为解决这个问题的更好方法是通过在 C++17 中被标准化为 std::is_detected

的检测习惯用法

C++11

首先我们需要一些辅助结构和类型别名来实现检测习惯用法:

template<class...>
using void_t = void;

template<typename T, typename=void_t<>>
struct HaspPrintMethod : std::false_type{};

template<typename T>
struct HaspPrintMethod<T, void_t<decltype(std::declval<T>().pPrint(std::declval<std::ostream&>()))>> : std::true_type{};

template<typename T>
using HaspPrintMethod_t = typename HaspPrintMethod<T>::type;

并检查 toString:

template<typename T, typename=void_t<>>
struct HasToStringMethod : std::false_type{};

template<typename T>
struct HasToStringMethod<T, void_t<decltype(std::declval<T>().toString())>> : std::true_type{};

template<typename T>
using HasToStringMethod_t = typename HasToStringMethod<T>::type;

然后我们简化标签分发调用:

 pPrint(T m)
 {
     CallPrint(m, HaspPrintMethod_t<T>());
 }

如果没有 pPrint 方法可用,我们将输入 std::false_type 标签,然后我们进一步调度:

void CallPrint(const T& m, std::false_type)
{
    CallPrintNopPrint(m, HasToStringMethod_t<T>());
}

private:
void CallPrintNopPrint(const T& m, std::true_type)
{
    buf = m.toString();
}
void CallPrintNopPrint(const T& m, std::false_type)
{
    buf = "NO print Function";
}

Live Demo

我们的测试:

LD ld = { "And", "Ap" };
UP  up = { "James Brannd", "jamens@goo.com" };

// this should print "Name: James Email: jamens@goo.com"
std::cout << pPrint <UP> (up) << std::endl;

// this should print "Username: And Password: Ap"
std::cout << pPrint <LD> (ld) << std::endl;

// this should print "NO print Function";
struct Foo{};
Foo f;
std::cout << pPrint<Foo>(f) << std::endl;

输出:

Name: James Brannd Email: jamens@goo.com
Username: And Password: Ap
NO print Function

(事实上,我可能会将所有 CallPrint 方法隐藏为 private,因为我不希望用户调用它们,但我保留了现有的方法,因为OP就是这样)


C++17

我们的检测习语将使用 std::is_detectedconstexpr if

Demo

(我认为编译器还不支持 [[maybe_unused]] attribute specifier,否则我会使用它并消除警告)

template<class T>
using HasPrintMethod = decltype(std::declval<T>().pPrint(std::declval<std::ostream&>()));
template<class T>
using HasToStringMethod = decltype(std::declval<T>().toString());

 // ...
constexpr pPrint(T m)
{
    if constexpr(is_detected<HasPrintMethod, T>::value)
    {
        std::ostringstream  os;
        m.pPrint(os);
        buf = os.str();
    }
    else
    { 
        if constexpr (is_detected<HasToStringMethod, T>::value)
        {
           buf = m.toString();
        }
        else
        {
           buf = "NO print Function";
        }
    }
}

您可以使用另一个 integral_constant 来获得您想要的优先级

template <class T>
class pPrint {
    public:


    pPrint(T m)
    {
        CallPrint(m, std::integral_constant<bool, HaspPrintMethod<T>::Has>(), std::integral_constant<bool, HastoString<T>::Has>());
    }

    void CallPrint(const T& m, std::true_type, std::true_type)
    {
        std::ostringstream  os;
        m.pPrint(os);
        buf = os.str();
    }

    void CallPrint(const T& m, std::true_type, std::false_type)
    {
        std::ostringstream  os;
        m.pPrint(os);
        buf = os.str();
    }

    void CallPrint(const T& m, std::false_type, std::true_type)
    {
        buf = m.toString();
    }

    void CallPrint(const T& m, std::false_type, std::false_type)
    {
        buf = "No print function";
    }

    std::string buf;
};

live demo