为什么在 std::initializer_list 中编译给出关于函数模板专业化的注释?
Why compile give note in std::initializer_list regarding function template specialization?
我使用 std::initializer_list
写了一个 printf
函数:
template<typename T, typename... Ts>
auto printf(T t, Ts... args) {
std::cout << t << std::endl;
return std::initializer_list<T>{([&] {
std::cout << args << std::endl;
}(), t)...};
}
int main() {
printf(111, 123, "alpha", 1.2);
return 0;
}
编译器给出函数模板特化实例化的注释:
warning: returning address of local temporary object [-Wreturn-stack-address]
return std::initializer_list<T>{([&] {
^~~~~~~
note: in instantiation of function template specialization 'printf<int, int, const char *, double>' requested here
printf(111, 123, "alpha", 1.2);
我知道 return 使用堆栈地址是一种不好的做法,但是,如果我不这样做 return 那么我将收到:
warning: expression result unused [-Wunused-value]
我如何更改我的代码以避免这三种类型的编译器警告?
How could I change my code to avoid these three type of compiler warnings?
不要 return 对象并使用好的旧 (void)
技巧(有关更多信息,请参见例如 this thread):
(void) std::initializer_list<T>{ /* ... */ };
顺便说一下,printf
实现非常棒 :)
将 initializer_list 转换为 void 以向编译器表明您没有故意使用它
我使用 std::initializer_list
写了一个 printf
函数:
template<typename T, typename... Ts>
auto printf(T t, Ts... args) {
std::cout << t << std::endl;
return std::initializer_list<T>{([&] {
std::cout << args << std::endl;
}(), t)...};
}
int main() {
printf(111, 123, "alpha", 1.2);
return 0;
}
编译器给出函数模板特化实例化的注释:
warning: returning address of local temporary object [-Wreturn-stack-address]
return std::initializer_list<T>{([&] {
^~~~~~~
note: in instantiation of function template specialization 'printf<int, int, const char *, double>' requested here
printf(111, 123, "alpha", 1.2);
我知道 return 使用堆栈地址是一种不好的做法,但是,如果我不这样做 return 那么我将收到:
warning: expression result unused [-Wunused-value]
我如何更改我的代码以避免这三种类型的编译器警告?
How could I change my code to avoid these three type of compiler warnings?
不要 return 对象并使用好的旧 (void)
技巧(有关更多信息,请参见例如 this thread):
(void) std::initializer_list<T>{ /* ... */ };
顺便说一下,printf
实现非常棒 :)
将 initializer_list 转换为 void 以向编译器表明您没有故意使用它