【问题标题】:Is template enable_if function implementation possible? [duplicate]模板 enable_if 函数实现是否可行? [复制]
【发布时间】:2023-03-15 16:15:02
【问题描述】:

使用 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,因为它们是不敬虔的。

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

【问题讨论】:

  • 为什么不用标签调度?
  • 发帖的人已经回答了这个问题,这不是真的。链接的问题甚至没有单独使用声明和实现。
  • 那么,你的实际问题是如何定义一个使用 SFINAE 的外联函数,对吧?
  • @NathanOliver 是的:)
  • 那么这基本上是thisthis的欺骗

标签: c++ c++11 c++14 sfinae enable-if


【解决方案1】:

你真的不需要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";
}

Live on Coliru

或类似的东西,比如 constexpr if:

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";
}

Live on Coliru

【讨论】:

  • 部分函数特化?..
  • 没有偏特化,@bipll
  • 我正在努力完成这项工作,但事实并非如此。我的函数是成员函数,我认为它们不符合条件。
  • @scx 他们可能是,只是显示真实的声明。
  • 它是一样的,在一个可变参数结构中。更新问题。
【解决方案2】:

此时 enable_if 信息丢失。

它没有丢失,在这两种情况下都是int。只有一个模板没有被实例化。

【讨论】:

    猜你喜欢
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2012-01-22
    • 2017-01-06
    • 1970-01-01
    • 2015-05-02
    • 2012-03-20
    相关资源
    最近更新 更多