简体   繁体   中英

Template function specialization based on static member type

I don't have a lot of experience with templates but I am wondering if the following scenario is possible. Assume we have a class S with static member stat. I can get it to dynamically generate different code using typeid as:

template &ltclass S>
    void foo() 
    { 
        if (typeid(S::stat) == typeid(AType))
            implementation 1;
        else
            implementation 2;
    }

But since all information is known at compile time is it possible to create a specialization of foo for S::stat being of type Atype?

You're probably looking to do something like this:

template<typename T> class foo_impl {

public:

    static void foo()
    {
          // This is your implementation 2
    }
};

template<> class foo_impl<AType> {

public:

    static void foo()
    {
          // This is your implementation 1
    }
};

template <class S>
    void foo() 
    {
        foo_impl<typename S::Stat>::foo();
    }

One common way of solving this problem is through tag dispatching. We can, at compile time, produce different types for whether or not S::stat matches AType - and use those types to call different overloads:

template <class S>
void foo() {
    foo_impl(std::is_same<decltype(S::stat), AType>{});
}

void foo_impl(std::true_type /* S::stat matches AType */) {
    // implementation 1
}

void foo_impl(std::false_type /* S::stat doesn't match AType */) {
    // implementation 2
}

I was not able to utilize the decltype solution because my compiler does not support it.

I was able to utilize the foo_impl class solution but only when I declare MyClass as:

class MyClass { public: typedef AType Stat; static const Stat stat = VAL; ... }

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