【发布时间】:2018-06-10 13:41:50
【问题描述】:
下面的代码应该说明你是否可以在参数中使用模板化函数 typedef...
#include <vector>
struct vec2
{
float x, y;
};
struct dvec2
{
double x, y;
};
template <typename T>
void function(std::vector<T>& list, decltype(T::x) scalarVal, decltype(T::x) scalarVal2)
{
typedef decltype(T::x) scalarType;
scalarType a; // a is now a double or float depending on template argument
}
int main()
{
std::vector<vec2> vecOfVec2;
std::vector<dvec2> vecOfDvec2;
function(vecOfVec2, 0.f, 1.f);
function(vecOfDvec2, 0.0, 1.0);
}
所以你可以看到在函数中我做了一个typedef:
typedef decltype(T::x) scalarType;
然后使用scalarType 表示float 或double。如果我可以将函数的函数参数列出为:
void function(std::vector<T>& list, scalarType scalarVal, scalarType scalarVal2)
但是看起来好像直到在函数内部才创建 typedef ,这是行不通的。如果不可能,这样做是否可以接受:
(decltype(T::x) scalarVal, ...)
对于每次我在示例中展示的方式的参数?
【问题讨论】:
标签: c++ function templates typedef