【发布时间】:2019-06-04 16:45:35
【问题描述】:
这是我目前拥有的代码:
class Foo
{
public:
template<typename T, typename... Args>
void Function(T t1, Args... args){
// Definition
}
private:
template<typename T>
void Function(T t1){
// Definition
}
};
#include "header.h"
int main()
{
Foo foo;
foo.Function(1, 2, 3, 4, 5);
return 0;
}
工作得很好。当我尝试将定义与 source.cpp 分开时,gcc 开始抱怨。我知道我必须专门化模板才能分离定义,所以我尝试将以下代码添加到头文件中:
template<>
void Foo::Function<int, int...>(int t1, int... args);
template<>
void Foo::Function<int>(int);
但没有成功。我错过了什么
编辑:gcc 错误消息:
header.h:15:28: 错误:扩展模式‘int’不包含参数 包装 void Foo::Function(int t1, int... args);
header.h:15:48: 错误:扩展模式‘int’不包含参数 包装 void Foo::Function(int t1, int... args);
【问题讨论】:
-
你想达到什么目的?
-
“不起作用” 不是有用的问题描述。请在此处提供minimal reproducible example 重现问题(包括逐字错误消息)。
-
int...是不允许的。...用于扩展模板参数包,int..不是模板。void f(int...x)不能是函数,因为没有具体的签名。你想用Function做什么?也许std::initializer_list可以用来代替包,或者只是std::vector<int> -
@Quimby 最终结果应该类似于:
Function(std::string id, make_pair("key", "value"), make_pair("another_key", "another_value"), ...); -
@Quimby 无需专业化就可以正常工作。我要做的就是将方法定义移动到单独的源文件中。
标签: c++ templates variadic-templates