gpt4 book ai didi

c++ - C++ 宏中的模板?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:02:32 25 4
gpt4 key购买 nike

是否可以这样做

# define abc<T1> __abc<T1, T2>

template<typename T2> void somefun() {
...
abc<int>(...);
abc<double>(...);
...
}

只是为了不要每次调用 abc 时都写它

最佳答案

在 C++11 中你可以这样做:

template<typename T2> void somefun() {
template <typename T>
using abc = __abc<T, T2>;
}

没有它,您可以使用宏,但您需要这样做:

#define abc(T1) __abc<T1, T2>

//usage:

abc(Type) instance;

但由于这看起来不太自然,我个人会避免使用它。

如果你想避免使用 C++11 之前的宏,你可以这样做:

template <typename T2>
struct type {
template <typename T1>
struct lookup {
typedef __abc<T1,T2> type;
};
};

template <typename T2> void somefun() {
typedef type<T2> abc;
typename abc::template lookup<int>::type();
}

但老实说,它的可读性甚至比宏观情况还差

(注意:__abc是保留的)

关于c++ - C++ 宏中的模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10531497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com