1

我的代码有一个小问题。我尝试使用可变参数创建一个函数,但是当我编译它时,它失败了,我真的不明白为什么。所以如果有人可以帮助我...

这是我的功能:

查询集.hpp:

template <typename T>
class QuerySet
{
   template<typename U,typename ... Args>
   QuerySet& filter(const std::string& colum,Args ... args,const std::string& operation, const U& value);
   //...
}

template<typename T>
template<typename U,typename ... Args>
QuerySet<T>& QuerySet<T>::filter(const std::string& colum,Args ... args,const std::string& operation, const U& value)
{
     //some job
     return *this;
}

main.cpp QuerySet 查询集;queryset.filter(Perso::_master,Perso::_lvl,"gt",4); //第 135 行

注意: Perso::_master 和 Perso::_lvl 是一些静态的 const std::string;

错误:

g++ -g -std=c++0x -I"/my_path/cpp-ORM" -lmysqlcppconn   -o main.o -c main.cpp;
main.cpp: In function ‘int main(int, char**)’:
main.cpp:135:46: erreur: no matching function for call to ‘orm::QuerySet<Perso>::filter(const string&, const string&, const string&, int)’
main.cpp:135:46: note: candidate is:
/my_path/QuerySet.hpp:18:23: note: template<class U, class ... Args> orm::QuerySet<T>& orm::QuerySet::filter(const string&, Args ..., const string&, const U&) [with U = U, Args = {Args ...}, T = Perso, std::string = std::basic_string<char>]

信息:我使用 gcc 版本 4.6.4 (Ubuntu/Linaro 4.6.4-1ubuntu1~12.04),但我尝试使用 gcc4.8,但我有一个错误。

4

2 回答 2

4

可变参数包必须出现在函数签名的末尾,而不是中间。

为了更好地理解,请阅读: Variadic function template with pack expansion not in last parameter

于 2013-09-17T14:06:25.333 回答
3

永远无法调用您的函数,这是无法推断模板参数的上下文:

n3337, 14.8.2.1/1 [temp.deduct.call]

模板实参推导是通过将每个函数模板形参类型(称为 P)与调用的相应实参类型(称为 A)进行比较来完成的,如下所述。
[...]
对于出现在参数声明列表末尾的函数参数包,将调用的每个剩余参数的类型 A 与函数参数包的声明符 ID 的类型 P 进行比较。每个比较推导出模板参数包中由函数参数包扩展的后续位置的模板参数。对于没有出现在参数声明列表末尾的函数参数包,参数包的类型是非推导上下文。
[...]

将参数包移动到函数参数列表的末尾。

您可以明确指定模板参数,但我认为这不是您想要的。例如:

q.filter<int, int, int>("oi", 1, 2, "oi", i);
于 2013-09-17T14:11:42.527 回答