Zeb*_*ish 4 c++ templates typedef function
下面的代码应该显示我的意思是你是否可以在参数中使用模板化函数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);
}
Run Code Online (Sandbox Code Playgroud)
所以你可以看到我在函数中创建了一个typedef:
typedef decltype(T::x) scalarType;
Run Code Online (Sandbox Code Playgroud)
然后scalarType
用来表示float
或者double
.如果我能列出函数的函数参数,我会发现它很有用:
void function(std::vector<T>& list, scalarType scalarVal, scalarType scalarVal2)
Run Code Online (Sandbox Code Playgroud)
但是看到好像在函数内部之前没有生成typedef,这将无效.如果不可能,这是可以接受的:
(decltype(T::x) scalarVal, ...)
Run Code Online (Sandbox Code Playgroud)
对于每次我在示例中显示它的方式的参数?
然后使用"scalarType"表示float或double.如果我能列出函数的函数参数,我会发现它很有用:
这不起作用,因为标量类型取决于矢量类型.如果你在那里省略类型依赖,你怎么知道哪种类型是正确的?无论哪种方式,您必须提供您使用的矢量类型.
如果不可能,这是可以接受的:
Run Code Online (Sandbox Code Playgroud)(decltype(T::x) scalarVal, ...)
对于每次我在示例中显示它的方式的参数?
有更好的选择.这样,您可以使函数的接口依赖于内部数据表示,而不是建议.实现可能会有所不同,实现可能会发生变化,而破坏性更改会使接口无效.此外,对于使用您的代码而不了解其内部的任何其他人,他/她将必须实际检查实现细节以找出您实际意义的内容.相反,你可以在每个向量中定义一个通用名称,即
struct dvec {
using scalarType = double;
...
};
struct vec2 {
using scalarType = float;
...
};
template <typename T>
void foo(typename T::scalarType bar) { ... }
Run Code Online (Sandbox Code Playgroud)
这是整个STL中使用的一种非常常见的模式.
归档时间: |
|
查看次数: |
114 次 |
最近记录: |