gpt4 book ai didi

C++ 创建通用模板函数特化

转载 作者:行者123 更新时间:2023-11-28 03:57:34 25 4
gpt4 key购买 nike

我知道如何专门化一个模板函数,但是我想在这里做的是为所有具有给定方法的类型专门化一个函数,例如:

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

template<typename T, if_exists(T::bar)>void foo(){...}//always use this one if the method T::bar exists

我的类中的 T::bar 是静态的并且具有不同的返回类型。

我尝试通过为我的类派生一个空基类(“class HasBar{};”)来做到这一点,并在我的“专业”版本上使用 boost::enable_if 和 boost::is_base_of。然而,问题是对于有 bar 的类,编译器无法决定使用哪一个 :(。

template<typename T>
typename boost::enable_if<boost::is_base_of(HasBar, T>, void>::type f()
{...}

我知道我可以在“普通”版本上使用 boost::disable_if,但是我不控制普通版本(它由第三方库提供,预计会进行特化,我只是不我真的很想为我的 20 个左右的类进行显式特化),我也没有太多控制使用这些函数的代码,只有实现 T::bar 的类和使用它的函数。

有没有办法告诉编译器在不改变其他版本的情况下“无论如何都尽可能使用这个版本”?

编辑:我尝试了一种使用模板类和显式特化的不同方法,但这显然也是不允许的...无论如何要使这种方法起作用?

template<typename T>class ImpFoo
{
public:
//error C3637: 'foo' : a friend function definition cannot be a specialization of a function template
template<> friend void foo<T>(){...}
};
...
class SomeClass : public ImpFoo<T>
{
...
SomeType bar(){...}
};

最佳答案

遗憾的是,在这种情况下,您运气不佳,您能做的最好的事情就是像@aaa 所说的那样明确地专门化模板。
由于您可以将这些特化限制为向一个中央函数的简单转发,因此 20 个类的开销应该是可以承受的。例如:

template<class T> my_foo() { /* do the actual work */ }

template<> void foo<MyClass01>() { my_foo<MyClass01>(); }
// ...
template<> void foo<MyClass20>() { my_foo<MyClass20>(); }

关于C++ 创建通用模板函数特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2887713/

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