【发布时间】:2019-07-15 16:19:09
【问题描述】:
背景:
我正在开发一个查询 DSL,它将解析带有 ==、< 等的表达式,并通过运算符重载返回过滤器对象。
问题:
与字符串文字一起使用时,我的模板方法失败。我尝试提供模板的特定实例化同时采用std::string 和char,但似乎都不起作用。
代码如下。在 main 中导致问题的行标有注释。我尝试过的替代解决方案在代码中被注释掉。
可以在here找到相同代码的可运行repl。
我确实知道用std::string("text") 手动包装字符串文字会起作用,但如果可能的话,我希望能够使用纯字符串文字。
#include <iostream>
template<typename T>
struct Filter;
struct Field
{
Field(const std::string &val): name(val) { }
Field(std::string &&val): name(std::move(val)) { }
std::string name;
// template <signed N>
// Filter<std::string> operator==(const char (&val) [N]);
template <typename T>
Filter<T> operator==(const T &val);
};
template <typename T>
Filter<T> Field::operator==(const T &val)
{
return Filter<T>{ *this, val, "==" };
}
// template <signed N>
// Filter<std::string> Field::operator==(const char (&val) [N])
// {
// return Filter<std::string>{ *this, std::string(val), "==" };
// }
// template <>
// Filter<std::string> Field::operator==<std::string>(const std::string &val)
// {
// return Filter<std::string>{ *this, val, "==" };
// }
template<typename T>
struct Filter
{
Field f;
T val;
std::string op;
};
int main() {
Field f1 { "field1" };
Field f2 { "field1" };
std::cout << (f1 == 1).val;
std::cout << (f1 == "Hello").val; // <--- the source of my problems
}
【问题讨论】: