可以使用以下形式调用模板化成员函数(参数列表中未使用模板参数):
struct C { template <class> func (); };
C c;
C.func <int>();
Run Code Online (Sandbox Code Playgroud)
但是如何调用模板构造函数,它在参数列表中不使用模板参数?
struct D { template <class> D (); };
Run Code Online (Sandbox Code Playgroud)
当然
D<int> d;
Run Code Online (Sandbox Code Playgroud)
不能是语法,因为这是类型变量的构造D <int>,它是类模板的实例化 D<class>.
这不仅仅是一个学术问题,我用于模板化构造函数(不使用构造函数参数列表中的模板),基本上是基于策略的工厂,目前使用伪参数mpl::identity <mytype>()作为变通方法.
使用g ++ 3.4和4.7,我观察到以下奇怪的行为:
如果需要用户定义的转换,则函数模板不匹配,其中普通函数将是.我在C++ 98标准中找不到相应的规则.g ++是否正确,(我假设)?或者这是一个错误?
template <class T>
int x(auto_ptr_ref<T> p)
{
return 1;
}
// this would match
/*
int x(auto_ptr_ref<int> p)
{
return 2;
}
*/
void dummy()
{
cout << x(auto_ptr<int>()) << endl;
}
Run Code Online (Sandbox Code Playgroud) c++ templates function overload-resolution implicit-conversion
如何编写需要成员函数模板且必须提供模板参数的 C++ 20 概念?
以下概念的目标是检查类型是否类似于元组,除非std::get<I>(t)我想检查而不是检查t.get<I>()。
以下内容不会使用 switch 与 g++ 10.1 一起编译-std=c++2a。
#include <concepts>
template <typename E>
concept Tpl = requires(E const e, int idx)
{
{
e.template get<idx>()
} -> std::convertible_to<float>;
};
Run Code Online (Sandbox Code Playgroud)
如果template之前没有使用过get,它当然不会编译(没有尖括号,小于/大于运算符)。