gpt4 book ai didi

c++ - 模板类型定义?

转载 作者:行者123 更新时间:2023-12-02 00:53:15 25 4
gpt4 key购买 nike

在外部 API 中,我定义了结构: Foo1 , Foo4 , Foo8 , Foo16

现在我需要定义四个函数:

void bar(Foo1*);
void bar(Foo4*);
void bar(Foo8*);
void bar(Foo16*);

这些函数在迭代 1、4、8 和 16 次的循环中执行相同的操作。

为了避免将这些函数编写 4 次,我很乐意使用模板来定义它们:

template<unsigned int N> void bar(Foo<N> * foo)
{
for(unsigned int i=0;i<N;++i)
{
//Some critical code that optimizes nicely with SSE, AVX, etc...
}
}

但是,我不知道如何定义模板类Foo<N>这样它就专门用于 Foo1 , Foo4 , Foo8 , Foo16

可能吗?

我知道我可以创建一个模板结构:

template<unsigned int N> struct Foo;
template<> struct Foo<1>{ Foo1 f; };
template<> struct Foo<4>{ Foo4 f; };
template<> struct Foo<8>{ Foo8 f; };
template<> struct Foo<16>{ Foo16 f; };

这在功能上与我想要实现的目标相同,但有点膨胀 bar代码,其中将充满 foo.f s,并依赖于 FooN* 的强制转换至Foo<N>* .

最佳答案

I don't know how to define the template class Foo so that it's specialized to Foo1, Foo4, Foo8, Foo16

像这样:

template <int N> struct Foo_impl {};
template <> struct Foo_impl<1 > {using type = Foo1 ;};
template <> struct Foo_impl<4 > {using type = Foo4 ;};
template <> struct Foo_impl<8 > {using type = Foo8 ;};
template <> struct Foo_impl<16> {using type = Foo16;};
template <int N> using Foo = typename Foo_impl<N>::type;

但问题是模板参数推导不适用于这样的别名:

template <int N> void bar(Foo<N> *foo) {}

int main()
{
Foo<4> x;
bar(&x); // error: no matching function for call to 'bar'
// note: candidate template ignored: couldn't infer template argument 'N'
}

要使其正常工作,您必须使用类似 template <typename T> void bar(T *foo) {} 的内容,带有 static_assert (或其他一些技巧)限制 T这 4 种类型之一。

你可以这样做:

template <typename T> void bar(T *foo)
{
constexpr int N =
std::is_same_v<T, Foo1 > ? 1 :
std::is_same_v<T, Foo4 > ? 4 :
std::is_same_v<T, Foo8 > ? 8 :
std::is_same_v<T, Foo16> ? 16 : throw "Invalid T.";
// ...
}

在这里,throw "Invalid T."实际上不会在运行时抛出,但如果 T 则导致编译时错误不是 Foo# 之一.

关于c++ - 模板类型定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59929177/

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