相关疑难解决方法(0)

在非推导的上下文中解决模板参数的方法

请考虑以下代码:

#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>::innernondeduced背景(如解释在这里),这意味着模板参数的类型不能被编译器推导出(读这个答案的原因).在我看来,我有两个选项让它工作:

  1. 移动inner到外面outer并使其成为类模板.我更喜欢这个,因为对使用代码的影响较小.
  2. to_string在内部添加一个方法.

是否有任何其他解决方案(在使用代码中不会导致丑陋的语法)?

c++ templates template-argument-deduction

15
推荐指数
1
解决办法
1089
查看次数