【问题标题】:How is it possible to use the type of a template parameter's member?如何使用模板参数成员的类型?
【发布时间】:2017-02-26 14:14:24
【问题描述】:

我的函数如下所示:

template<typename T, typename U>
T myfunc(T a, T b) {
    // the type of a.data and b.data is U
    // ...
}

TU 类型的示例如下所示:

class ExampleT {
public:
    int data;
};

其中T 是类,它有一个名为data 的成员。而data的类型是U

我的函数现在必须使用两个类型参数调用:

myfunc<T, U>(...);

但是第二个类型参数(U)是第一个类型(T)中data变量的类型。是否可以从模板中删除U,并使用decltype 检测它?

可以使用所有最新的 C++14 功能。

【问题讨论】:

  • 请问有什么意义?如果需要,为什么不使用本地 typedef?
  • 你想对会员做什么?答案可以简单到auto x = a.data;
  • 我想将一个变量转换为它的类型,然后再将它分配给data
  • 你可以只使用 static_cast(blahblahblah)。无需将其设为模板参数。

标签: c++ templates visual-c++ c++14


【解决方案1】:

您可以将其推断为默认模板参数:

template<typename T, typename U = decltype(T::data)>
T myfunc(T a, T b) {
    // the type of a.data and b.data is U
    // ...
}

Demo;或者在函数体内:

template<typename T>
T myfunc(T a, T b) {
    using U = decltype(T::data);
    // ...
}

或者使用本地类型定义,如 Columbo 的 suggested

struct ExampleT {
    using Type = int;
    Type data;
};

template<typename T, typename U = typename T::Type>
T myfunc(T a, T b) {
    // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2018-04-06
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多