简体   繁体   中英

C++: “Inferring” template type from a dependent type

I have a class:

class MyClass{
    enum Choices : int
    {
        First,
        Last
    };
    template<MyClass::Choices choice>
    void bar(...);
};

I want to be able to make a choice -templated call to bar() in the client code. Now since I don't want the client code to be in charge of managing the MyClass instances, I want to add another layer to be responsible for that, so that I would have:

{
   t = new T();
   t.bar<choice>();
};

inside the function.

Ideally, I would like to be able to call this layer, let's call it foo() , like this:

foo<MyClass::Choices::One>(...);

Is this possible? This is what I tried and am getting errors:

template<typename T>
template<T::Choices choice>
void foo(){
   t = new T();
   t.bar<choice>();
};

I believe this is the best you can do using the idea of traits:

#include <iostream>
#include <type_traits>

template <typename T>
struct choice_traits;

class MyClass{
public:
    enum Choices : int
    {
        First,
        Last
    };
    template<MyClass::Choices choice>
    void bar(...) {}
};

template <>
struct choice_traits<MyClass::Choices>
{
    using parent = MyClass;
};

template <MyClass::Choices C>
using choice_const = std::integral_constant<MyClass::Choices, C>;

template <typename C, C value>
void foo(std::integral_constant<C, value>)
{
    using T = typename choice_traits<C>::parent;

    T* t = new T();

    t->template bar<value>();
}

int main()
{
    foo(choice_const<MyClass::Choices::First>());

    return EXIT_SUCCESS;
}

You need to specialize choice_traits for each container class that has an enum of choices. I also created a helper choice_const in order to avoid directly using std::integral_constant .

It could be improved upon if there was more information but that's as much as can be done based on your explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM