简体   繁体   中英

how to use std::enable_if correctly in this case

I have the following method defined:

template <typename Interface>
Interface Create();

with this implementation:

template <typename Interface>
typename std::enable_if<std::is_pointer<Interface>::value, Interface>::type Create()
{
...
}

but now I get the following errors: "undefined reference to ITestInterface* Create()"

when I remove the std::enable_if , everything works fine. But I require it to work since I want to add versions of this function that work when Interface is a reference or when Interface is a std::vector . What am I doing wrong here? I also noticed that this is a linker error - but I don't know why. Can someone give me a hint?

Whereas in normal function, return type doesn't be part of signature, return type does be part of signature for template function.
So

template <typename Interface> Interface Create();

differs than

template <typename Interface>
typename std::enable_if<std::is_pointer<Interface>::value, Interface>::type
Create();

You have to use same signature in declaration and definition.

As partial specialization is not possible on function, you have to use helper class: Something like may help:

namespace detail
{

template <typename > struct CreateHelper;

template <typename T> struct CreateHelper<T*>
{
    static T* create() {
        // Implementation with T*
    }
};

template <typename T> struct CreateHelper<T&>
{
    static T& create() {
        // Implementation with T&
    }
};

template <typename T> struct CreateHelper<std::vector<T>>
{
    static std::vector<T> create() {
        // Implementation with std::vector<T>
    }
};

} // namespace detail


template <typename Interface> Interface Create()
{
    return detail::CreateHelper<Interface>::create();
}

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