在类自己的成员函数中构造类时,如何强制类模板参数推导?
How to force class template argument deduction when constructing a class in its own member functions?
请考虑以下代码:
struct A {};
template <typename T> struct B
{
B(T) {}
auto foo() {return B(A{});} // error: no matching function for call to 'B<int>::B(A)'
};
auto foo() {return B(A{});} // compiles
int main()
{
foo();
B b(0);
b.foo();
}
现场试用
我理解为什么B::foo()
不编译:在struct B<T>
内部,B
(作为注入的类名(表示B<T>
,除非它明确用作模板。在这种情况下,这可以防止类模板参数推断。
假设我不能做auto foo() {return B<A>(A{});}
因为我的实际代码依赖于稍微复杂的用户提供的演绎指南。
问题是:在B::foo
内部构造B
时如何强制类模板参数推导?
我希望我没有错过一些明显的东西。
你限定它,以便它不是注入的类名。
auto foo() {return ::B(A{});}
另一种选择是使用函数为您进行类型推断。
template <typename T> B<T> make_b(T t) { return B<T>(t); }
和使用
auto foo() {return make_b(A{});}
相关文章:
- 函数作为模板参数,是否对返回类型强制约束
- 如何在不强制转换每个参数的情况下删除初始值设定项列表中从 int 到 char 的缩小转换?
- 是否可以在运行时强制转换模板参数?
- 将强制转换简化为取决于参数的类型
- 编译器是否强制根据模板参数计算表达式?
- 如何使用可变参数模板强制转换每个变体类型
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 是否可以在调用链接器时强制 CMake 重新排序参数?
- 传递可变参数时在成员初始值设定项列表中强制转换
- 在类自己的成员函数中构造类时,如何强制类模板参数推导?
- 将参数隐式强制转换为布尔
- C++:我可以在模板参数包中强制执行至少1个agment吗
- 将函数应用于元组中的每个元素,将每个元素强制转换为类型包中的不同类型,然后作为参数包传递
- 将ctypes c_void_p强制转换为c输出参数
- 为什么或何时应在调用之前将可调用函数参数强制转换为右值?
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 如何强制函数仅接受左值引用参数
- 当超出列时,clang格式强制每个参数/参数拥有自己的行?
- 哪个强制转换应与模板类参数一起使用,dynamic_cast或reinterpet_cast?
- 如何强制对模板参数类型进行签名