Bjö*_*lex 15 c++ templates template-argument-deduction
请考虑以下代码:
#include <iostream>
template<class T>
struct outer {
struct inner {};
};
template<class T>
std::ostream& operator<<(std::ostream & stream,
typename outer<T>::inner const& value) {
std::cout << "An outer::inner!";
return stream;
}
int main() {
outer<float>::inner foo;
std::cout << foo << std::endl; // does not compile
}
Run Code Online (Sandbox Code Playgroud)
这不编译,因为typename outer<T>::inner是nondeduced背景(如解释在这里),这意味着模板参数的类型不能被编译器推导出(读这个答案的原因).在我看来,我有两个选项让它工作:
inner到外面outer并使其成为类模板.我更喜欢这个,因为对使用代码的影响较小.to_string在内部添加一个方法.是否有任何其他解决方案(在使用代码中不会导致丑陋的语法)?
Joh*_*itb 23
您可以将运算符移动到内部类主体中并放在friend它之前.然后用just替换参数类型inner.
另一种技术是从内部参数化的CRTP基础派生内部.然后使参数键入CRTP类并将参数引用强制转换为派生inner类,派生类的类型由您推导出的模板参数给出.