所以,我试图写一个这样的函数:
void append_to_stream(std::ostream &stream)
{ }
template <typename T, typename... Args>
void append_to_stream(std::ostream &stream, T first, Args&&... rest)
{
stream << first;
append_to_stream(stream, rest...);
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
append_to_stream(stream,
std::endl,
std::endl);
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我收到一个错误,指出该函数的"参数太多".我把它缩小到我知道这std::endl是有罪的地步- 可能是因为它是一个功能.我设法通过声明一个被调用的结构来"解决"这个问题endl并定义<<operator它以便它只是调用它std::endl.这有效,但感觉不是特别好.是不是可以接受std :: endl作为模板参数?该功能适用于其他类型.
编辑:这是错误:
src/log/sinks/file_sink.cpp:62:21: error: too many arguments to function ‘void log::sinks::append_to_stream(std::string&, Args&& ...) [with Args = {}, std::string = std::basic_string<char>]’
Run Code Online (Sandbox Code Playgroud)
更新
试图让编译器推导出正确的模板参数@MooingDuck建议可以使用以下形式的函数:
template<class e, class t, class a>
basic_ostream<e,t>&(*)(basic_ostream<e,t>&os) get_endl(basic_string<e,t,a>& s)
{
return std::endl<e,t>;
}
Run Code Online (Sandbox Code Playgroud)
但是,这不编译.
错误:
src/log/sinks/file_sink.cpp:42:28: error: expected …Run Code Online (Sandbox Code Playgroud) 以下是两个模板函数,它们的模板参数不同.其余参数完全相同.
template<int module>
void template_const(int &a,int & b){
a = a & module;
b = b % module;
}
template<bool x>
void template_const(int &a,int & b){
int w;
if (x){
w = 123;
}
else w = 512;
a = a & w;
b = b % w;
}
Run Code Online (Sandbox Code Playgroud)
当我试图像这样打电话给他们
template_const<true>(a,b)
Run Code Online (Sandbox Code Playgroud)
要么
template_const<123>(a,b)
Run Code Online (Sandbox Code Playgroud)
编译器告诉我调用是不明确的.我怎么称呼这两个功能?
码:
#include <iostream>
template<typename T>
void out() // line 4
{
}
template<typename T, typename... Args>
void out(T value, Args... args) // line 9
{
std::cout << value;
out(args...); // line 12
}
int main()
{
out("12345", std::endl); // line 17
return 0;
}
Run Code Online (Sandbox Code Playgroud)
构建错误:
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -pthread -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
../main.cpp: In function ‘int main()’:
../main.cpp:17:24: error: no matching function for call to ‘out(const char [6], <unresolved overloaded function type>)’ …Run Code Online (Sandbox Code Playgroud)