首页 > 解决方案 > 模板 enable_if 函数实现是否可行?

问题描述

使用 c++14,我有一些类似于以下的函数声明。

template <class... Args>
struct potato {
template <class T, class = std::enable_if_t<!std::is_same<T, int>::value>>
const T& blee(size_t blou) const;

template <class T, class = std::enable_if_t<std::is_same<T, int>::value>>
const T& blee(size_t blou) const;
};

是否可以单独实现这些功能?据我所知,编译器无法弄清楚是什么实现了什么。例如 :

template <class... Args>
template <class T, class>
const T& potato<Args...>::blee(size_t blou) const {
    // do something
}

template <class... Args>    
template <class T, class>
const T& potato<Args...>::blee(size_t blou) const {
    // do something
}

那时信息就丢失了enable_if。我是否在我的工具包中遗漏了一个技巧来完成这项工作?请注意,我宁愿不使用返回类型enable_if或参数enable_if,因为它们是不虔诚的。

编辑:更新以更好地代表我的用例。

标签: c++c++11c++14sfinaeenable-if

解决方案


你真的不需要enable_if那个:

template<class T>
const T& blee(size_t blou) const {
    // do something
}

template<>
const int& blee<int>(size_t blou) const {
    // do something
}

编辑:由于您的函数位于类模板中,因此您必须使用标签调度:

template<class... Args>
struct potato {
    template<class T>
    void blee() const;

private:
    void realBlee(std::true_type) const;
    void realBlee(std::false_type) const;
};

template<class... Args>
template<class T>
void potato<Args...>::blee() const {
    realBlee(std::is_same<T, int>());
}

template<class... Args>
void potato<Args...>::realBlee(std::true_type) const {
    std::cout << "int\n";
}
template<class... Args>
void potato<Args...>::realBlee(std::false_type) const {
    std::cout << "generic\n";
}

住在科利鲁

或类似的东西,例如 constexpr 如果:

template<class... Args>
struct potato {
    template<class T>
    void blee() const;

private:
    void intBlee() const;
};

template<class... Args>
template<class T>
void potato<Args...>::blee() const {
    if constexpr (std::is_same_v<T, int>) {
        intBlee();
    } else {
        std::cout << "generic\n";
    }
}

template<class... Args>
void potato<Args...>::intBlee() const {
    std::cout << "int\n";
}

住在科利鲁


推荐阅读