gpt4 book ai didi

c++ - 有没有办法为函数模板特化命名类型?

转载 作者:行者123 更新时间:2023-11-28 02:49:43 24 4
gpt4 key购买 nike

例如,当我们有一个通用的函数模板时,我们可以在函数中使用模板类型:

template <typename T>
void foo()
{
T t;
...
}

现在,想象一下这个函数模板的特殊化:

template <>
void foo<MySpecialType>()
{
T t; // Does not compile, no knowledge of formal template argument T
MySpecialType t2; // This is OK, but I have to mention MySpecialType again
}

template <>
void foo<MySpecialType2>()
{
T t; // Does not compile, no knowledge of formal template argument T
MySpecialType2 t2; // This is OK, but I have to mention MySpecialType2 again
}

请注意,在上面的两个特化中,我必须提到在函数体内按名称特化的模板参数的类型。我更愿意使用更通用的占位符(即 T),而不是在函数模板特化的主体中重复(可能多次)特化的类型。

如果有一种方法可以在实际专门化函数定义时使用 T 或创建别名,那就太好了。我知道我可以通过实际函数体内的类型别名来做到这一点:

template<>
void foo<MySpecialType>
{
using T=MySpecialType; // But then I still repeat the type at least once
...

我更喜欢像这样的特化约定:

// Warning: Not valid C++
template<>
void foo<T=MySpecialType>
{
T t;
...

或者:

// Warning: Not valid C++
template<T>
void foo<MySpecialType>
{
T t;
...

感谢您的任何建议。

最佳答案

你可以这样做:

template <typename T>
struct bar
{
using Type = T;

static void foo();
};

template <typename T>
void bar<T>::foo()
{
Type t;
// ...
}

template <>
void bar<MySpecialType>::foo()
{
Type t;
// ...
}

template <>
void bar<MySpecialType2>::foo()
{
Type t;
// ...
}

template <typename T>
void foo()
{
bar<T>::foo();
}

但你真的需要它吗?

关于c++ - 有没有办法为函数模板特化命名类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23348949/

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