Ambiguous Function Calls to C++ base classes

前端 未结 3 404
旧巷少年郎
旧巷少年郎 2021-02-05 11:53

I\'m trying to create a variadic templated class which provides a method for each class in the typelist. An example is shown below which creates a print method for

3条回答
  •  后悔当初
    2021-02-05 12:22

    To resolve the ambiguity, it is possible to do

    template 
    struct Printer : PrintHelper...
    {
        template 
        void print (const U& t)
        {
            PrintHelper::print (t);
        }
    };
    

    (see an example )

    but this is not quite as robust as one would hope. In particular, you cannot print an object which is convertible to one of the types from the type list.

    With some template metaprogramming, it is possible to dispatch to the correct printer however. To do this you have to select a type from Ts... to which U is convertible, and call the right PrintHelper, ie.

    PrintHelper::type>::print (t);
    

    where find_convertible is defined by

    template 
    struct find_convertible
    {};
    
    template 
    struct find_convertible :
        std::conditional<
            std::is_convertible::value, 
            std::common_type, // Aka identity
            find_convertible
        >::type
    {};
    

    (see example)

提交回复
热议问题