【问题标题】:Template deduction failure模板扣减失败
【发布时间】:2015-12-28 00:47:33
【问题描述】:

我正在尝试从 boost 库中实现绑定功能。 下面你可以看到主要结构 bind_t 定义了operator()

我的问题如下:为什么我们要在decltype中指定返回类型operator()返回类型call()显式作为成员函数(如果我在call之前删除this->,模板参数推导失败g++。)

也很有趣,使用 clang++ 就没有这样的问题。

我不知道为什么会这样。

template <typename F, typename  ... P>
struct bind_t {
private:
    std::tuple<typename holder<P>::type...> p;
    F func;
    template <size_t ... N, typename ... Args>
    auto call(index_list<N ...>, Args const& ... args) const -> decltype(func(std::get<N>(p)(args...)...)) {
        return func(std::get<N>(p)(args...)...);
    }
public:
    bind_t(F f, P ... p):
        p(std::move(p)...),
        func(std::move(f))
    {}
    template <typename ... Args>
    auto operator()(Args const& ... args) const -> decltype(this->call(typename indices_by_num<sizeof...(P)>::type(), args...)) {
        typename indices_by_num<sizeof...(P)>::type indices;
        return call(indices, args...);
    }
};

full source 实施
simple usecase

【问题讨论】:

  • 看起来它已在 gcc 5.1 中修复

标签: c++ templates gcc variadic-templates sfinae


【解决方案1】:

这是一个 gcc 错误,并记录在错误报告 decltype needs explicit 'this' pointer in member function declaration of template class with trailing return type 中:

当对模板的成员函数使用尾随返回类型时 类,必须明确提及“this”指针。这应该 没有必要(隐含的“this”适用于非模板 类)。

例子:

template <typename T>
struct DecltypeConstThis {

    T f() const { return T{}; }

    auto g() -> decltype(this->f()) { return this->f(); }
    auto h() const  ->  decltype(f()) { return f(); } // this should work the same as g() above (with implicit 'this')

};

struct Working {
    int f() const { return 0; }
    auto h() const -> decltype(f()) { return 0; }
};


int main() {

    Working w;
    w.h();

    DecltypeConstThis<int> d;
    d.g();
    d.h();

    return 0;
}

该报告被标记为已修复,看起来这项工作在 gcc 5.1 中开始工作 (see it live)。

【讨论】:

  • 如果您没有最新版本的 gcc,您可以使用Wandbox 进行验证,并查看它开始使用的版本。
猜你喜欢
  • 2018-02-19
  • 2012-10-30
  • 2013-06-20
  • 1970-01-01
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
相关资源
最近更新 更多