gpt4 book ai didi

c++ - 模板函数重载 : enable_if for CRTP, 编译器坚持选择泛型函数

转载 作者:行者123 更新时间:2023-12-03 20:53:28 30 4
gpt4 key购买 nike

这是一个模型案例,其中有一个通用函数 func然后(人道地说)更专业的功能func对于派生自 Base 的类通过 CRTP,仅通过 enable_if 为适当的参数类型启用.

#include<type_traits>
#include<iostream>

// CRTP hierarchy
template<class T> class Base{ };
class Derived: public Base<Derived>{};

// overload 1
template<class T> void func(const T& a){ std::cerr<<"1\n"; }
// overload 2
template<class T, typename std::enable_if<std::is_base_of<Base<T>,T>::value,int>::type* = nullptr>
inline void func(const Base<T>& obj){ std::cerr<<"2\n"; }

int main(void){ func(Derived()); }

然而,编译器仍然认为第一个重载是更好的匹配。我明白 enable_if仅启用该功能,但不会使其更好地解决重载问题。

很抱歉,我无法从 Function template 中理解很多意义C++ 引用部分。

谁能建议如何让编译器更喜欢第二个函数?

谢谢!

编辑:动机:在实际使用中,这些函数应该处理各种标量和数组类型(尤其是使用 CRTP 的 Eigen)。标量应该涵盖所有数字类型,如整数、 float ……(不枚举它们),而另一个重载应该涵盖数组——同样,不枚举它们,但知道它们都派生自 Eigen::DenseBase<Derived> .

最佳答案

只需使用 constexpr ifs 从单个公共(public)函数中选择正确的函数。

C++17

namespace
{
template<typename T>
inline void base_func( const T& derived );

template<typename T>
inline void other_func( const T& otherType );
}

template<typename T>
inline void func( const T& type )
{
if constexpr( std::is_base_of_v<Base<T>, T> )
base_func( type );
else
other_func( type );
}

C++14 使用特征

namespace
{
template<typename T>
inline void base_func( const T& derived );

template<typename T>
inline void other_func( const T& otherType );

template <bool B>
struct func_select_trait;

template <>
struct func_select_trait<true>
{
template <typename T>
static void call( const T& derived ) { base_func<T>( derived ); }
};

template <>
struct func_select_trait<false>
{
template <typename T>
static void call( const T& otherType ) { other_func<T>( otherType ); }
};

}

template<typename T>
inline void func( const T& type )
{
func_select_trait<std::is_base_of<Base<T>, T>::value>::call<T>( type );
}

关于c++ - 模板函数重载 : enable_if for CRTP, 编译器坚持选择泛型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61231067/

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