Ite*_*tor 2 c++ templates visual-c++ c++14
我的功能看起来像这样:
template<typename T, typename U>
T myfunc(T a, T b) {
// the type of a.data and b.data is U
// ...
}
Run Code Online (Sandbox Code Playgroud)
类型的例子T和U看起来像这样:
class ExampleT {
public:
int data;
};
Run Code Online (Sandbox Code Playgroud)
T这个类的名称在哪里data?而且类型data是U
我的函数必须在目前使用两个类型参数调用:
myfunc<T, U>(...);
Run Code Online (Sandbox Code Playgroud)
但第二种类型参数(U)是data第一种类型(T)内的变量类型.是否有可能U从模板中删除并检测它,例如使用decltype?
可以使用所有最新的C++ 14功能.
您可以将其推断为默认模板参数:
template<typename T, typename U = decltype(T::data)>
T myfunc(T a, T b) {
// the type of a.data and b.data is U
// ...
}
Run Code Online (Sandbox Code Playgroud)
演示 ; 或者在函数体内:
template<typename T>
T myfunc(T a, T b) {
using U = decltype(T::data);
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者使用Columbo 建议的本地typedef
struct ExampleT {
using Type = int;
Type data;
};
template<typename T, typename U = typename T::Type>
T myfunc(T a, T b) {
// ...
}
Run Code Online (Sandbox Code Playgroud)