【问题标题】:Reordering of an overloaded Template function重载模板函数的重新排序
【发布时间】:2018-06-19 10:03:24
【问题描述】:

我有一个使用外部函数bind 的类InsertStatement

namespace sqlite {

template <typename T>
inline void bind(SQLiteStatement &statement, size_t idx, const T &value) {
    statement.bind(idx, value);
}

template<typename ...FIELDS>
class InsertStatement {

   ...
   template <typename T>
   bool bindValue(int idx, const T& t) {
       sqlite::bind(*statement, idx+1, t);
       return true;
   }
   ...
};

使用外部函数的原因是能够覆盖它并支持在InsertStatement类中使用其他类型。例如,如果我想将它与StrongType&lt;T&gt; 一起使用,我可以这样做:

template <typename T, typename TAG>
class StrongType {
private:
    T value;
public:
    StrongType (T&& v)
            : value(std::forward<T>(v)) {

    }

    T toValue() const
    {
        return value;
    }
};

namespace sqlite {

template <typename T, typename TAG>
inline void bind (SQLiteStatement &statement, size_t s, const StrongType<T,TAG> &strongType) {
    statement.bind(s, strongType.toValue());
}
}

问题是我需要包含StrongType.h before InsertStatement.h,否则编译器无法正确解析函数调用。

虽然我可以直观地解释它,但问题是,我该如何避免这个问题?我不想从#include "StrongType.h"InsertStatement.h,因为StrongType 是一个与这个库没有直接关系的外部类,因为这确实会发生在任何新类型上,我想让这个类足够灵活。

我正在使用不同的编译器(gcc、clang 和 MSVC)、c++14(c++17 或更高版本暂时不是一个选项)。

  1. 如何避免这种“标题排序”问题?
  2. 让 Templated 类扩展为其他类型的最佳方法是什么?

【问题讨论】:

    标签: c++ templates c++14 template-meta-programming


    【解决方案1】:

    您可能依赖于ADL,并且bindStrongType 在同一命名空间中。
    (你不需要使用合格的调用):

    template <typename T>
    bool bindValue(int idx, const T& t) {
        using sqlite::bind;
        bind(*statement, idx+1, t);
        return true;
    }
    

    【讨论】:

    • 谢谢,但这不是问题所在。要编译,我需要在泛型bind 之前使用StrongType 参数定义bind,否则编译器将尝试使用泛型版本实例化某些东西。我认为这与两阶段查找有关,但我对此一无所知,我不明白是否如此。谢谢
    • 不应该每次使用template&lt;typename ...FIELDS&gt; InsertStatement::bindValue时都可见。
    • 这正是我的想法。而且我不明白为什么它不起作用。那么,我将尝试提供一个最低限度的可编译示例。
    猜你喜欢
    • 1970-01-01
    • 2017-05-04
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    相关资源
    最近更新 更多