【问题标题】:Is there a way to typedef a type for template function arguments?有没有办法为模板函数参数类型定义类型?
【发布时间】: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 表示floatdouble。如果我可以将函数的函数参数列出为:

void function(std::vector<T>& list, scalarType scalarVal, scalarType scalarVal2)

但是看起来好像直到在函数内部才创建 typedef ,这是行不通的。如果不可能,这样做是否可以接受:

(decltype(T::x) scalarVal, ...)

对于每次我在示例中展示的方式的参数?

【问题讨论】:

    标签: c++ function templates typedef


    【解决方案1】:

    然后使用“scalarType”来表示浮点或双精度。如果我可以将函数的函数参数列出为:

    这是行不通的,因为标量类型取决于向量类型。如果你忽略了类型依赖,你怎么知道哪种类型是正确的?无论哪种方式,您都必须在某处提供您使用的矢量类型。

    如果不可能,这样做是否可以接受:

    (decltype(T::x) scalarVal, ...)
    

    对于每次我在示例中展示的方式的参数?

    有更好的选择。这样,您可以使函数的接口依赖于内部数据表示,这不是建议性的。实现可能会有所不同,实现可能会改变,而破坏性的改变会以这种方式使接口无效。此外,对于使用您的代码但不知道其内部结构的任何其他人,他/她将不得不实际检查实现细节以找出您的实际含义。 相反,您可以在每个向量内定义一个通用名称,即

    struct dvec {
        using scalarType = double;
        ...
    };
    
    struct vec2 {
        using scalarType = float;
        ...
    };
    
    template <typename T>
    void foo(typename T::scalarType bar) { ... }
    

    这是在整个 STL 中使用的非常常见的模式。

    【讨论】:

    • 我明白了。所以基本上你是说在结构本身中有 typedef 。我认为这非常聪明,也是一个很好的解决方案。
    • 不错。正如答案中已经提到的,这种方法类似于 STL 容器 中的value_type 成员类型(例如,std::vectorstd::list 等)和 STL 容器适配器(例如,std::stackstd::queue 等)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    相关资源
    最近更新 更多